F#歧视联盟中的函数(Functions in F# Discriminated Unions)

编程入门 行业动态 更新时间:2024-10-17 11:33:27
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 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]

更多推荐

本文发布于:2023-07-06 07:38:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1047400.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   联盟   Functions   Discriminated   Unions

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!