[Haskell-cafe] Re: Is this haskelly enough?

Jonathan Cast jcast at ou.edu
Wed Jul 18 11:38:43 EDT 2007

On Wednesday 18 July 2007, Johan Tibell wrote:
> It would be nice if it was possible to capture this kind of behavior in a
> high order function just like map though. I guess the problem is that the
> function to map will take different number of arguments depending on the
> use case.
> lookAtTwo a b = ...
> lookAtThree a b c = ...
> map' :: (a -> ... -> b) -> [a] -> [b]
> The parameter take a variable number of parameters.
> Note: I don't know if there is a sensible way to write map' at all. Perhaps
> explicit recursion is better in this case.

Variable number of parameters?

data Mapper alpha beta
  = Yield beta
  | Consume (alpha -> Mapper alpha beta)
genMap :: Mapper alpha beta -> [alpha] -> [beta]
genMap m = flip fix m $ \ loop m' xn -> case (m', xn) of
  (Yield y, xn) -> y : loop m xn
  (Consume f, []) -> []
  (Consume f, x : xn) -> loop (f x) xn

Discards the last few elements of the list if there aren't enough, but you can 

genMap (Consume $ \ x -> Consume $ \ y -> Yield $ f x y) xn

if you want, and you can even get true C-style varargs out of this.

A little verbose, but non-obvious techniques often are.

Jonathan Cast

More information about the Haskell-Cafe mailing list