gpt4 book ai didi

functional-programming - ocaml中的复合函数

转载 作者:行者123 更新时间:2023-12-04 05:09:28 26 4
gpt4 key购买 nike

如何使用函数式语言(尤其是Ocaml)定义复合函数?例如,如果我编写一个函数来计算另一个函数结果的求反,即:not(f(x))其中f(x)返回一个 bool 值。我该如何定义?

最佳答案

给定一些函数f,其类型为:

f: 'a -> bool

您希望能够生成另一个函数来包装它以使结果取反。让我们考虑一下这个新函数的类型,我们将其称为 negated(我不使用 not,因为它是内置函数的名称):
negated: ('a -> bool) -> 'a -> bool

为什么是这种类型?为什么不使用 'a -> bool?很好记住,我们希望这个新函数接受一个现有函数并返回一个具有相同类型但执行不同操作的新函数。为了更清楚地看到它,您可以这样想:等效的 ('a -> bool) -> ('a -> bool)

因此,现在鉴于这些限制,我们如何编写 negated函数?
let negated f = ??

好吧,我们首先必须考虑该函数需要返回一个函数:
let negated f = (fun x -> ??)

接下来是什么?好吧,我们知道我们创建的新函数应该使用参数调用包装函数并将其取反。让我们这样做,使用参数 f x调用该函数,并将其取反: not (f x)。这给了我们最终的函数定义:
let negated f = (fun x -> not (f x))

让我们来看看它的作用:
# let f x = x < 5;;
val f : int -> bool = <fun>
# f 2;;
- : bool = true
# f 8;;
- : bool = false
# let negated f = (fun x -> not (f x));;
val negated : ('a -> bool) -> 'a -> bool = <fun>
# let g = negated(f);;
val g : int -> bool = <fun>
# g 2;;
- : bool = false
# g 8;;
- : bool = true

关于functional-programming - ocaml中的复合函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4997661/

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