oad*_*ams 2 haskell variadic typeclass function-composition
我想创建一个函数apply,它接受一个具有任意数量参数的函数以及一个整数列表,并返回函数的结果(其中列表中的每个整数按顺序是一个参数.
我想的是:
apply :: ([Int] -> Int) -> [Int] -> Int
apply f x:xs = apply (f x) xs
apply f [] = f
Run Code Online (Sandbox Code Playgroud)
但我知道这不会起作用,因为类型签名是错误的 - 函数不会获取整数列表,它只需要一些int参数.
另外,当我到达基本情况时,apply的f参数实际上应该是一个整数,无论如何都违反了类型签名.
有谁知道如何处理这类问题?
Don*_*art 11
我想创建一个函数apply,它接受一个具有任意数量参数的函数以及一个整数列表,
你为什么要这样做?也许您的参数结构应该作为数据结构传递,但到目前为止,您已经过度约束了该问题,以确保它不会产生惯用的Haskell解决方案.
您可以使用一些奇特的类型来完成它
{-# LANGUAGE FlexibleInstances #-}
-- for ApplyType (Int -> r)
class ApplyType t where
apply :: t -> [Int] -> Int
instance ApplyType Int where
apply f _ = f
instance (ApplyType r) => ApplyType (Int -> r) where
apply f (x:xs) = apply (f x) xs
main :: IO ()
main = do print $ apply ((+) :: Int->Int->Int) [1, 2]
print $ apply ((\x y z w -> x*y - z`div`w) :: Int->Int->Int->Int->Int) [3,5,8,2]
Run Code Online (Sandbox Code Playgroud)