Tuesday, May 11, 2010

Implicit Folds in Haskell (for those jealous of LISP)

Ever wish you could do things like (+ 3 4 5) from LISP, but in Haskell? Wish no more with the beautiful FoldyList datatype! An example instance for Show is given but feel free to write your own, otherwise the code is next to useless.

module FoldyList where
data FoldyList a =
FoldyCons (FoldyHead a) (FoldyTail a)
type FoldyHead a = (a -> a -> a)
type FoldyTail a = [a]
instance Show q => Show (FoldyList q) where
show (FoldyCons x y) = show $ foldr1 x y
flist :: FoldyList Int
flist = FoldyCons (+) [3,4,5]
main = print flist
view raw FoldyList.hs hosted with ❤ by GitHub

2 comments:

  1. I wouldn't call it FoldyCons, as that appears to be confusing. You're not really Cons'ing, so much as applying.

    Maybe, FoldyBuild?

    ReplyDelete
  2. Hmm... how is FoldyCons (+) [3,4,5] better than just writing foldr1 (+) [3,4,5] in the first place?

    ReplyDelete