Home > Enterprise >  Haskell have a function accept an unknown number of argument as parameter
Haskell have a function accept an unknown number of argument as parameter

Time:01-08

I need my function to called like so: myFunc 1 5 4 3 6 2 7 8 9 5 1 3 or myFunc 2 6 4

How do write my types so it accepts an unknown number of parameters and put them in a list ? I want to do something like this:

myFunc :: Int -> IO ()  -- I don't know what type to put replace Int with 
myFunc a = 
    return a

myFunc 1 2 5 4 8 should return [1,2,5,4,8]

CodePudding user response:

Functions that can accept an “unknown number of arguments” are called variadic functions. Haskell doesn't support variadic functions, but it has a sufficiently flexible type system to be able to fake them.

This is known as “the printf trick” and widely considered to be an awkward hack. Think twice whether you really want this – it is not idiomatic Haskell, it may lead to weird error messages, and there are plenty of alternative approaches that would probably work as well or better for you.

That out of the way, here's how to do it:

{-# 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
  •  Tags:  
  • Related