[Haskell-cafe] Recursion in Haskell

Brandon S. Allbery KF8NH allbery at ece.cmu.edu
Sat Feb 17 21:36:08 EST 2007


On Feb 17, 2007, at 21:32 , P. R. Stanley wrote:

> Hi
> I understand the basic principle of recursion but have difficulty  
> with the following:
> -- a recursive function
> -- for calculating the length of lists
> myLen [] = 0
> myLen (x:xs) = 1 + myLen xs
> What's happening here?

This definition uses pattern matching.  The first one matches an  
empty list; the second matches a list using constructor syntax (a  
list [a,b,c] in constructor syntax is a:b:c:[]) in order to extract  
the first element and the rest of the list into separate variables  
"x" and "xs", then recursively invokes itself on xs.

The "x" being unused, that definition can also be rewritten as:

myLen (_:xs) = 1 + myLen xs

since _ can be used in a pattern match as a placeholder.

-- 
brandon s. allbery    [linux,solaris,freebsd,perl]     allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university    KF8NH





More information about the Haskell-Cafe mailing list