[Haskell-cafe] Haskell Style - Pattern Matching with case vs. function declarations

Gwern Branwen gwern0 at gmail.com
Wed Mar 18 13:59:20 EDT 2009


On Wed, Mar 18, 2009 at 1:49 PM, Tom.Amundsen <tomamundsen at gmail.com> wrote:
>
> Hi All,
>
> I am new to Haskell. I just started reading "Real World Haskell" a few days
> ago, so I apologize for being such a noob.
>
> But, I am curious why I see a lot of code where people do pattern matching
> via multiple function declarations instead of using the case ... of ...
> construct? For example:
>
> [code]
> foldl' _    zero []     = zero
> foldl' step zero (x:xs) =
>      let new = step zero x
>      in  new `seq` foldl' step new xs
> [/code]
>
> instead of this, which I prefer:
>
> [code]
> foldl' f acc xs = case xs of
>                            [] -> acc
>                            (x:xs) -> let new = f acc x
>                                          in  new `seq` foldl' f new xs
> [/code]

Personally, I prefer the former for several reasons: it has less syntax (no case...of...->...-> stuff), it's easier to manipulate textually, it's less indented, and it's somewhat mentally easier to follow, since case feels imperative and step-by-step.

Might as well ask why people prefer guard syntax to nesting if-then-elses; sure, they may be converted into the same code under the hood and be equivalent in power, but one scales better (in terms of clarity).

-- 
gwern
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 270 bytes
Desc: OpenPGP digital signature
Url : http://www.haskell.org/pipermail/haskell-cafe/attachments/20090318/16d52ea5/signature.bin


More information about the Haskell-Cafe mailing list