F#歧视联盟中的函数(Functions in F# Discriminated Unions)
有没有办法在歧视联盟中使用职能? 我期待着做这样的事情:
Type Test<'a> = Test of 'a-> bool
我知道这在Haskell中可能使用newtype,我想知道F#中的等价物是什么。
谢谢。
Is there a way to use functions in Discriminated Unions? I am looking to do something like this:
Type Test<'a> = Test of 'a-> bool
I know this is possible in Haskell using newtype and I was wondering what the equivalent in F# would be.
Thanks.
最满意答案
作为desco的答案的一个扩展,你可以使用模式匹配将函数塞入Test中:
type Test<'a> = Test of ('a -> bool) // let applyTest T x = match T with Test(f) -> f x // better: (as per kvb's comment) pattern match the function argument let applyTest (Test f) x = f x例:
// A Test<string> let upperCaseTest = Test (fun (s:string) -> s.ToUpper() = s) // A Test<int> let primeTest = Test (fun n -> let upper = int (sqrt (float n)) n > 1 && (n = 2 || [2..upper] |> List.forall (fun d -> n%d <> 0)) )在FSI中:
> applyTest upperCaseTest "PIGSMIGHTFLY";; val it : bool = true > applyTest upperCaseTest "PIGSMIgHTFLY";; val it : bool = false > [1..30] |> List.filter (applyTest primeTest);; val it : int list = [2; 3; 5; 7; 11; 13; 17; 19; 23; 29]As an expansion on desco's answer you can apply the function tucked into Test with pattern matching:
type Test<'a> = Test of ('a -> bool) // let applyTest T x = match T with Test(f) -> f x // better: (as per kvb's comment) pattern match the function argument let applyTest (Test f) x = f xExample:
// A Test<string> let upperCaseTest = Test (fun (s:string) -> s.ToUpper() = s) // A Test<int> let primeTest = Test (fun n -> let upper = int (sqrt (float n)) n > 1 && (n = 2 || [2..upper] |> List.forall (fun d -> n%d <> 0)) )In FSI:
> applyTest upperCaseTest "PIGSMIGHTFLY";; val it : bool = true > applyTest upperCaseTest "PIGSMIgHTFLY";; val it : bool = false > [1..30] |> List.filter (applyTest primeTest);; val it : int list = [2; 3; 5; 7; 11; 13; 17; 19; 23; 29]更多推荐
发布评论