Haskell 有一个函数接受未知数量的参数作为参数

BLS*_*SPR 0 haskell types

我需要像这样调用我的函数: 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
Run Code Online (Sandbox Code Playgroud)

myFunc 1 2 5 4 8 应该返回 [1,2,5,4,8]

lef*_*out 5

可以接受 \xe2\x80\x9c 未知数量的参数\xe2\x80\x9d 的函数称为可变参数函数。Haskell 不支持可变参数函数,但它有足够灵活的类型系统来伪造它们。

\n

这被称为 \xe2\x80\x9cprintf技巧\xe2\x80\x9d,并被广泛认为是一个尴尬的黑客行为。请三思而后行,您是否真的想要这个 \xe2\x80\x93 它不是惯用的 Haskell,它可能会导致奇怪的错误消息,并且有很多替代方法可能对您同样有效或更好。

\n

不碍事,下面是如何做到这一点:

\n
{-# LANGUAGE TypeFamilies #-}\n\nclass MyFuncType a where\n  myFuncAcc :: [Int] -> a\n\ninstance a ~ () => MyFuncType (IO a) where\n  myFuncAcc = print\ninstance (MyFuncType a, c ~ Int) => MyFuncType (c -> a) where\n  myFuncAcc l h = myFuncAcc $ h:l\n\nmyFunc :: MyFuncType a => a\nmyFunc = myFuncAcc []\n\nmain :: IO ()\nmain = myFunc 1 2 5 4 8\n
Run Code Online (Sandbox Code Playgroud)\n

  • 这是一个与你问的完全不同的问题。(与您所问的不同,可变参数_命令行参数_实际上是一个明智的选择。)使它成为一个新问题。 (6认同)