简体   繁体   中英

Functions in F# Discriminated Unions

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.

type Test<'A> = Test of ('A -> bool)

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 x

Example:

// 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM