Functions in F # Discriminatory Unions

Is there a way to use functions in Discriminative Unions? I want 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 is equivalent in F #.

Thank.

+3
source share
2 answers

As an extension on the desco answer, you can use the function hidden in 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 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]
+4
source
type Test<'A> = Test of ('A -> bool)
+5
source

Source: https://habr.com/ru/post/1777951/


All Articles