Haskell 有没有通用的方法来告诉函数的参数数量?

Tor*_*nny 4 parameters haskell types functional-dependencies

我可以用下面的代码告诉函数的参数数量

{-#Language MultiParamTypeClasses#-}
{-#Language FunctionalDependencies#-}
{-#Language UndecidableInstances#-}

data Zero
data Succ a

class Number a
instance Number Zero
instance (Number a) => Number (Succ a)

class NotFunction a
instance NotFunction Int
instance NotFunction Float
instance NotFunction (IO a)

class (Number n) => FunctionLevel f n | f -> n where
  functionLevel :: f -> n
instance FunctionLevel Int Zero where
  functionLevel = undefined
instance FunctionLevel Float Zero where
  functionLevel = undefined
instance FunctionLevel (IO a) Zero where
  functionLevel = undefined
instance FunctionLevel Double Zero where
  functionLevel = undefined
instance (FunctionLevel f' n) => FunctionLevel (a->f') (Succ n) where
  functionLevel = undefined
Run Code Online (Sandbox Code Playgroud)

我们得到:

*Main> :t functionLevel (undefined::a->b->Int)
functionLevel (undefined::a->b->Int) :: Succ (Succ Zero)
*Main> :t functionLevel (undefined::a->b->Double)
functionLevel (undefined::a->b->Double) :: Succ (Succ Zero)
*Main> :t functionLevel (undefined::a->b->c->d->IO a)
functionLevel (undefined::a->b->c->d->IO a)
  :: Succ (Succ (Succ (Succ Zero)))
*Main> :t functionLevel (undefined::a->b->c->d->Int)
functionLevel (undefined::a->b->c->d->Int)
  :: Succ (Succ (Succ (Succ Zero)))
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,functionLevel对于某些特殊类型“结束”的函数,其执行效果与我们预期的一样。我的问题是:我们可以概括这一点来告诉任意函数的参数号吗?

nus*_*hio 5

只是一个想法;您可以使用以下代码在值级别了解函数的参数数量。

https://gist.github.com/nushio3/5867066

import Data.Typeable
import Test.Hspec

arityOf :: Typeable a => a -> Int
arityOf x = go $ typeOf x
  where
    go tr
      | isFun $ typeRepTyCon tr = 1 + go (last $ snd $ splitTyConApp tr)
      | otherwise               = 0

    funTyCon = typeRepTyCon $ typeOf ((1+):: Int -> Int)
    isFun = (funTyCon ==)

main :: IO ()
main = hspec spec

func :: (Int -> Int) -> Int -> Int
func = undefined

spec :: Spec
spec = describe "arityOf" $ do
  it "evaluates Integers correctly" $ arityOf (1::Int) `shouldBe` 0
  it "evaluates Strings correctly" $ arityOf "(1::Int)" `shouldBe` 0
  it "evaluates monads correctly" $ arityOf main `shouldBe` 0
  it "evaluates multiplications correctly" $ arityOf ((*) :: Int -> Int -> Int)
    `shouldBe` 2
  it "is not deceived by non-tail argument" $ arityOf func `shouldBe` 2
Run Code Online (Sandbox Code Playgroud)