[Haskell-cafe] Sneaky method for var-arg fns?
Micah Cowan
micah at cowan.name
Fri Jul 26 23:08:06 CEST 2013
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
More information about the Haskell-Cafe
mailing list