Another Haskell question

Which pattern is more efficient?

Pattern a:

circleSumA :: [Int] -> Int
circleSumA (i1 : is) = aux i1 is
    where aux i [] = i + i1
          aux i is = i + aux (head is) (tail is)

Pattern b:

circleSumB :: [Int] -> Int
circleSumB is = sum (is ++ [head is])

Is the Haskell compiler/interpreter able to make pattern b as efficient as pattern a? What about in the more general case where the operation is operating on more than 2 list elements? e.g. Folding a dot product over a list of points (obviously taking three points at a time to compute the dot product of the two vectors formed). In this case, Pattern b would have to perform 2 list appends (is ++ [head is] ++ [head (tail is)]). Would these get optimised?

4 comments

  1. It's pretty nice. I first heard about its strong showings in recent ICFP programming contests. And I got interested when I discovered a real program written in it, viz. a GTK front end for Inform 7. I've been looking at FP lately, in particular purely applicative stuff, because ISTM that could be a good solution to getting parallelism on current and upcoming architectures.

    There are some online tutorials of course. I'm currently working my way through The Haskell School of Expression which is pretty good at more “real-world” stuff like drawing fractals in a window rather than writing factorial and prime sieving functions.

    (http://livejournal.com/users/elbeno)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.