是否可以在F#中编写默认函数

发布于 2024-08-12 05:25:23 字数 134 浏览 2 评论 0原文

默认或无点风格编程允许人们创建函数而不考虑它们的参数。这可以在 F# 中完成吗?

Tacit or point-free style programming allows one to create functions without regard to their arguments. Can this be done in F#?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

梅倚清风 2024-08-19 05:25:23

只是为了配合查克的回答&克里斯史密斯的评论,你可以写

let digits = string_of_int >> String.length
digits 9000;; // 4
[1; 10; 100] |> List.map digits;; // [1;2;3]

当你结合这些成分和具有高阶函数的管道运算符,您可以非常简洁地完成复杂的事情:

let prodSqrtAbs = Seq.map (abs>>sqrt) >> Seq.reduce (*)
prodSqrtAbs [| -9.0; 4.0 |];;  // 6.0

编辑:我刚刚读到有关 J 及其隐式分叉运算符的信息。那是非常强大的。您可以在 F# 中构建等效的高阶运算符,但它们不会隐式应用。因此,例如,首先定义 lift (使用显式参数)

let lift op a b x = op (a x) (b x)

,然后显式应用它

let avg = lift (/) List.sum List.length

以获得类似于 您链接到的维基百科页面上的 J 示例。但它并不完全“默契”。

Just to go with Chuck's answer & Chris Smiths' comment, you could write

let digits = string_of_int >> String.length
digits 9000;; // 4
[1; 10; 100] |> List.map digits;; // [1;2;3]

When you combine those composition & pipeline operators with higher-order functions, you can do complicated stuff very succinctly:

let prodSqrtAbs = Seq.map (abs>>sqrt) >> Seq.reduce (*)
prodSqrtAbs [| -9.0; 4.0 |];;  // 6.0

EDIT: I just read about J and its implicit fork operator. That is very powerful. You can build equivalent higher-order operators in F#, but they won't be applied implicitly. So, for example, first define lift (using explicit arguments)

let lift op a b x = op (a x) (b x)

and then apply it explicitly

let avg = lift (/) List.sum List.length

to get something resembling the J example on the Wikipedia page you linked to. But its not quite "tacit."

请恋爱 2024-08-19 05:25:23

当然。您所需要的只是函数组合和柯里化,而这两者在 F# 中都是可能的。

let compose f1 f2 = fun x -> f1 (f2 x);;
let digits = compose String.length string_of_int;;
digits 9000;; // 4

Sure. All you need is function composition and currying, and both of these are possible in F#.

let compose f1 f2 = fun x -> f1 (f2 x);;
let digits = compose String.length string_of_int;;
digits 9000;; // 4
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文