ocaml中的复合函数
如何用函数式语言(特别是 Ocaml)定义复合函数?例如,如果我编写一个函数来计算另一个函数结果的负数,即: not(f(x))
其中 f(x)
返回一个布尔值。我该如何定义它?
How can I define a composite function in a functional language, in particular with Ocaml? For example, if I write a function that calculates the negation of the result of another function, that is: not(f(x))
where f(x)
returns a boolean. How can I define it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
给定一些具有以下类型的函数
f
:您希望能够生成另一个函数来包装它以否定结果。让我们考虑一下这个新函数的类型,我们将其称为
neated
(我没有使用not
,因为它是内置函数的名称):为什么是这样的类型?为什么不
'a ->布尔?请记住,我们希望这个新函数接受现有函数并返回具有相同类型但执行不同操作的新函数。为了看得更清楚,你可以这样想:
('a -> bool) ->; ('a -> bool)
这是等价的。那么现在考虑到这些约束,我们如何编写
neated
函数呢?好吧,我们首先必须考虑这个函数需要返回一个函数:
接下来怎么办?好吧,我们知道我们创建的新函数应该使用参数调用我们的包装函数并将其取反。让我们这样做,使用参数调用函数:
f x
,并对其求反:not (fx)
。这给了我们最终的函数定义:让我们看看它的实际效果:
Given some function
f
, that has the type:you want to be able to generate another function to wrap it to negate the result. Let's consider the type for this new function, let's call it
negated
(I'm not usingnot
since it is the name of a builtin):Why is this the type? Why not
'a -> bool
? Well remember, we want this new function to take in an existing function and return a new function with the same type that does something different. To see it clearer, you can think of it like this:('a -> bool) -> ('a -> bool)
which is equivalent.So now given these constraints, how can we write the
negated
function?Well we first have to consider that this function needs to return a function:
What next? Well, we know that the new function we create should call our wrapped function with the argument and negate it. Let's do that, call the function with the argument:
f x
, and negate it:not (f x)
. That gives us the final function definition:Let's see it in action:
我不确定你到底想走多远——你编写的代码可以正常工作。因此,我将简单地一步步介绍如何从头开始编写这些内容。简单的否定就是:
你可以写
not (fx)
,它会给你f x
结果的否定。对于复合函数的函数,可以使用:
那么我们可以这样做:
I'm not sure exactly how far you're looking to go here — the code you wrote will work fine. So I'll give a simple step-by-step on how you write this stuff from scratch. Simple negation is just:
You can how write
not (f x)
and it will give you the negation of the result off x
.For a function that composes functions, you can use:
So then we can do:
哇,这些过于复杂的答案是怎么回事?有什么问题:
要获得
g(x) = not(f(x))
,假设您有一个f : 'a ->; bool
:此外,您可以做一些很酷的事情,例如:
现在
composite_function
的类型为int ->; int
,它的有效定义是:编辑:哦,我猜查克确实这样做了。我可能不应该只是略读。无论如何,我碰巧喜欢折叠撰写功能,所以我会继续这样做。 :p
Wow, what's with all of these overly complicated answers? What's wrong with:
To get your
g(x) = not(f(x))
, assuming you have anf : 'a -> bool
:Additionally, you can do cool stuff like:
Now the
composite_function
has typeint -> int
, and its effective definition is:EDIT: Oh, I guess Chuck actually did do this. I probably shouldn't have just skimmed. In any case, I happen to like folding over the compose function, so I'll keep this up. :p