gpt4 book ai didi

f# - 使用 F# 的默认编程风格

转载 作者:行者123 更新时间:2023-12-04 15:04:50 24 4
gpt4 key购买 nike

这实际上不是一个重要的问题,但我想看一个 tacit programming 的例子。在 F# 中,我的无点函数可以有多个参数(不是列表或元组的形式)。

其次,这些函数如何操作复杂的数据结构。我正在 F# Interactive 中尝试它,但还没有成功。

我试过,例如:

> (fun _ -> (fun _ -> (+))) 333 222 111 555

这是正确的方法吗?

和:
> (fun _ -> (fun _ -> (+))) "a" "b" "c" "d";;  

val it : string = "cd"

最佳答案

F# 不包含 Haskell 中可用的一些基本函数(主要是因为 F# 程序员通常更喜欢显式编程风格,并且仅在最明显的情况下才使用 pointfree 风格,在这种情况下不会损害可读性)。

但是,您可以像这样定义一些基本的组合器:

// turns curried function into non-curried function and back
let curry f (a, b) = f a b
let uncurry f a b = f (a, b)

// applies the function to the first/second element of a tuple
let first f (a, b) = (f a, b)
let second f (a, b) = (a, f b)

现在您可以使用组合子实现将两个字符串的长度相加的函数,如下所示:
let addLengths = 
uncurry (( (first String.length) >> (second String.length) ) >> (curry (+)))

这构造了两个应用 String.length 的函数到元组的第一个/第二个元素,然后组合它们,然后使用 + 添加元组的元素.整个东西都包裹在 uncurry ,所以你得到一个 string -> string -> int 类型的函数.

关于f# - 使用 F# 的默认编程风格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2793344/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com