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] [EMAIL PROTECTED]
system administrator [openafs,heimdal,too many hats] [EMAIL PROTECTED]
electrical and computer engineering, carnegie mellon university KF8NH
_______________________________________________
Haskell-Cafe mailing list
[email protected]
http://www.haskell.org/mailman/listinfo/haskell-cafe