Haskell: Function to determine the arity of functions?

后端 未结 6 631
一个人的身影
一个人的身影 2021-02-05 07:00

Is it possible to write a function arity :: a -> Integer to determine the arity of arbitrary functions, such that

> arity map
2
> arity fol         


        
6条回答
  •  不知归路
    2021-02-05 07:19

    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".

提交回复
热议问题