Haskell:确定函数的函数的函数? [英] Haskell: Function to determine the arity of functions?
本文介绍了Haskell:确定函数的函数的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以编写一个函数 arity :: a - > Integer
来确定任意函数的形式,例如
> arity map
2
> arity foldr
3
> arity id
1
> arityhello
0
?
OverlappingInstances :
{ - #LANGUAGE FlexibleInstances,OverlappingInstances# - }
类Arity f其中
arity :: f - > Int
实例Arity x其中
arity _ = 0
实例Arity f => Arity(( - >)af)其中
arity f = 1 + arity(f undefined)
更新发现问题。您需要为多态函数指定非多态类型:
arity(foldr ::(a - > Int - > Int)> Int> [a] - > Int)
不知道如何解决这个问题呢。
Upd2 由于Sjoerd Visscher在下面评论说:您必须指定非多态类型,因为答案取决于您选择哪种类型。
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
?
解决方案
It's easy with OverlappingInstances
:
{-# LANGUAGE FlexibleInstances, OverlappingInstances #-}
class Arity f where
arity :: f -> Int
instance Arity x where
arity _ = 0
instance Arity f => Arity ((->) a f) where
arity f = 1 + arity (f undefined)
Upd Found problem. You need to specify non-polymorphic type for polymorphic functions:
arity (foldr :: (a -> Int -> Int) -> Int -> [a] -> Int)
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".
这篇关于Haskell:确定函数的函数的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文