Haskell:确定函数数量的函数?
是否可以写一个函数 arity :: a -> Integer
确定任意函数的数量,这样
> arity map
2
> arity foldr
3
> arity id
1
> arity "hello"
0
?
Is it possible to write a function arity :: a -> Integer
to determine the arity of arbitrary functions, such that
> arity map
2
> arity foldr
3
> arity id
1
> arity "hello"
0
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
是的,它可以非常非常容易地完成:
原理:如果它是一个函数,您可以将它应用于恰好 1 个参数。请注意,haskell 语法使得不可能应用于 0、2 个或更多参数,因为 fa b 实际上是
(fa) b
,即不将f 应用于 a 和b
,但(f应用于a)应用于b
。当然,结果可能是另一个可以再次应用的函数,等等。
听起来很愚蠢,但这只是事实。
Yes, it can be done very, very easily:
Rationale: If it is a function, you can apply it to exactly 1 argument. Note that haskell syntax makes it impossible to apply to 0, 2 or more arguments as
f a b
is really(f a) b
, i.e. notf applied to a and b
, but(f applied to a) applied to b
.The result may, of course, be another function that can be applied again, and so forth.
Sounds stupid, but is nothing but the truth.
使用
OverlappingInstances
很容易:Upd发现问题。您需要为多态函数指定非多态类型:
还不知道如何解决这个问题。
Upd2 正如 Sjoerd Visscher 在下面评论的那样“您必须指定非多态类型,因为答案取决于您选择的类型”。
It's easy with
OverlappingInstances
:Upd Found problem. You need to specify non-polymorphic type for polymorphic functions:
Don't know how to solve this yet.
Upd2 as Sjoerd Visscher commented below "you have to specify a non-polymorphic type, as the answer depends on which type you choose".
如果
id
的arity为1,那么id x
不应该有arity 0吗?但是,例如,id map
与map
相同,在您的示例中,它的数量为 2。以下函数的数量相同吗?
我认为您对“数量”的概念没有明确定义......
If
id
has arity 1, shouldn'tid x
have arity 0? But, for example,id map
is identical tomap
, which would has arity 2 in your example.Have the following functions the same arity?
I think your notion of "arity" is not well defined...
在 Haskell 中,每个“函数”都只接受一个参数。看起来像“多参数”函数实际上是一个接受一个参数并返回另一个接受其余参数的函数的函数。所以从这个意义上说,所有函数的元数都是 1。
In Haskell, every "function" takes exactly one argument. What looks like a "multi-argument" function is actually a function that takes one argument and returns another function which takes the rest of the arguments. So in that sense all functions have arity 1.
对于标准 Haskell 来说这是不可能的。可以使用 IncoherentInstances 或类似的扩展。
但为什么要这样做呢?您不能询问函数需要多少个参数,然后使用这些知识来准确地给出该数量的参数。 (除非你使用 Template Haskell,在这种情况下,是的,我希望它在编译时是可能的。你使用 Template Haskell 吗?)
你想要解决的实际问题是什么?
It's not possible with standard Haskell. It may be possible using the IncoherentInstances or similar extension.
But why do you want to do this? You can't ask a function how many arguments it expects and then use this knowledge to give it precisely that number of arguments. (Unless you're using Template Haskell, in which case, yes, I expect it is possible at compile time. Are you using Template Haskell?)
What's your actual problem that you're trying to solve?
这个怎么样:
How about this: