有没有办法在Discriminated Unions中使用函数?我希望做这样的事情:
Type Test<'a> = Test of 'a-> bool
我知道在Haskell中使用newtype是可能的,我想知道F#中的等价物是什么。
感谢。
答案 0 :(得分:5)
type Test<'A> = Test of ('A -> bool)
答案 1 :(得分:4)
作为对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]