Haskell 有一个函数接受未知数量的参数作为参数
Haskell have a function accept an unknown number of argument as parameter
我需要像这样调用我的函数:
myFunc 1 5 4 3 6 2 7 8 9 5 1 3
要么
myFunc 2 6 4
如何编写我的类型以使其接受未知数量的参数并将它们放入列表中?
我想做这样的事情:
myFunc :: Int -> IO () -- I don't know what type to put replace Int with
myFunc a =
return a
myFunc 1 2 5 4 8
应该 return
[1,2,5,4,8]
可以接受“未知数量的参数”的函数称为 variadic functions。 Haskell 不支持可变参数函数,但它有足够灵活的类型系统来伪造它们。
这被称为“printf 技巧”,被广泛认为是一种尴尬的技巧。再三考虑你是否真的想要这个——它 不是 惯用的 Haskell,它可能会导致奇怪的错误消息,并且有很多替代方法可能同样有效或对你更好。
顺便说一句,这是如何做到的:
{-# LANGUAGE TypeFamilies #-}
class MyFuncType a where
myFuncAcc :: [Int] -> a
instance a ~ () => MyFuncType (IO a) where
myFuncAcc = print
instance (MyFuncType a, c ~ Int) => MyFuncType (c -> a) where
myFuncAcc l h = myFuncAcc $ h:l
myFunc :: MyFuncType a => a
myFunc = myFuncAcc []
main :: IO ()
main = myFunc 1 2 5 4 8
我需要像这样调用我的函数:
myFunc 1 5 4 3 6 2 7 8 9 5 1 3
要么
myFunc 2 6 4
如何编写我的类型以使其接受未知数量的参数并将它们放入列表中? 我想做这样的事情:
myFunc :: Int -> IO () -- I don't know what type to put replace Int with
myFunc a =
return a
myFunc 1 2 5 4 8
应该 return
[1,2,5,4,8]
可以接受“未知数量的参数”的函数称为 variadic functions。 Haskell 不支持可变参数函数,但它有足够灵活的类型系统来伪造它们。
这被称为“printf 技巧”,被广泛认为是一种尴尬的技巧。再三考虑你是否真的想要这个——它 不是 惯用的 Haskell,它可能会导致奇怪的错误消息,并且有很多替代方法可能同样有效或对你更好。
顺便说一句,这是如何做到的:
{-# LANGUAGE TypeFamilies #-}
class MyFuncType a where
myFuncAcc :: [Int] -> a
instance a ~ () => MyFuncType (IO a) where
myFuncAcc = print
instance (MyFuncType a, c ~ Int) => MyFuncType (c -> a) where
myFuncAcc l h = myFuncAcc $ h:l
myFunc :: MyFuncType a => a
myFunc = myFuncAcc []
main :: IO ()
main = myFunc 1 2 5 4 8