
Take a look at Text.Printf which takes this idea even further with its
printf function, which can accept an arbitrary number of arguments. This is
achieved by basically using your approach but with a recursive instance.
On Jul 26, 2013 10:10 PM, "Micah Cowan"
So, just for fun, I came up with a way to abuse the language in order to define a "function" whose argument is optional:
-- dirty-trick.hs - A sneaky way to do var args fns in Haskell
{-# LANGUAGE FlexibleInstances #-}
class Hello a where hello :: a
instance Hello (String -> String) where hello = (\str -> "Hello " ++ str)
instance Hello String where hello = hello "World"
In ghci,
putStrLn $ hello
gives "Hello World", while
putStrLn $ hello "There"
gives "Hello".
.
I was wondering if there was a way to do it in "pure" Haskell (i.e., no GHC pragmas required), and also the specific reason for why the above example doesn't work without the pragma (I think it's just that in general a -> b is not syntactically allowed for type specifiers within instance declarations)?
I'm also interested in alternative approaches to creating variable-argument functions, if there are any.
.
If anyone's curious, this was prompted by a discussion with a friend (copied), about Haskell and Clojure. He mentioned that Clojure can accept variable arguments, though AFAICT all Clojure functions basically act like they take a list (that supports variable types), so accepting an empty argument list is a bit analogous to Haskell accepting an empty list, rather than no arguments.
Part of the reason Haskell can't really take "variable arguments" is that all Haskell functions really just take one argument. But I figured you could use the contextually expected type to decide whether to return a simple value (not /technically/ a function in that case), or a function expecting further arguments, which could then be extended to define a function taking any arbitrary number of arguments.
Cheers! -mjc
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe