gpt4 book ai didi

f# - F# curry 函数

转载 作者:行者123 更新时间:2023-12-03 12:25:19 25 4
gpt4 key购买 nike

任何人都有一个体面的例子,最好是实际的/有用的,他们可以发表证明这个概念的例子吗?

最佳答案

(Edit: a small Ocaml FP Koan to start things off)

The Koan of Currying (A koan about food, that is not about food)

A student came to Jacques Garrigue and said, "I do not understand what currying is good for." Jacques replied, "Tell me your favorite meal and your favorite dessert". The puzzled student replied that he liked okonomiyaki and kanten, but while his favorite restaurant served great okonomiyaki, their kanten always gave him a stomach ache the following morning. So Jacques took the student to eat at a restaurant that served okonomiyaki every bit as good as the student's favorite, then took him across town to a shop that made excellent kanten where the student happily applied the remainder of his appetite. The student was sated, but he was not enlightened ... until the next morning when he woke up and his stomach felt fine.




我的示例将涵盖将其用于代码的重用和封装。一旦您看了这些,这是相当明显的,并且应该给您一个具体的,简单的示例,您可以考虑将其应用于多种情况。

我们想在树上绘制 map 。如果该函数需要一个以上的参数,则可以对该函数进行 curry 处理并将其应用于每个节点-因为我们将在节点上应用该函数作为其最终参数。不必着急,但是编写另一个函数(假设此函数在其他实例中与其他变量一起使用)将很浪费。
type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree
let rec tree_map f tree = match tree with
| N(x,left,right) -> N(f x, tree_map f left, tree_map f right)
| E(x) -> E(f x)

let sample_tree = N(1,E(3),E(4)
let multiply x y = x * y
let sample_tree2 = tree_map (multiply 3) sample_tree

但这与以下内容相同:
let sample_tree2 = tree_map (fun x -> x * 3) sample_tree

因此,这种简单情况并不令人信服。的确如此,并且一旦您更多地使用该语言,它自然就会遇到这些情况。另一个带有一些代码重用的示例。一个 recurrence relation to create prime numbers。那里有很多相似之处:
let rec f_recurrence f a seed n =
match n with
| a -> seed
| _ -> let prev = f_recurrence f a seed (n-1) in
prev + (f n prev)

let rowland = f_recurrence gcd 1 7
let cloitre = f_recurrence lcm 1 1

let rowland_prime n = (rowland (n+1)) - (rowland n)
let cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1

好的,现在rowland和cloitre是 curry 函数,因为它们具有自由变量,并且我们可以获取其序列的任何索引,而无需了解或担心f_recurrence。

关于f# - F# curry 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8448/

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