Guards as extensions of patterns

I never realized that a guard can be used as an extension of a pattern. Is this recommended coding? elem n xs asks whether n is an element of xs elem :: (Eq a) => a -> [a] -> Bool elem _ [] = False elem n (x:_) | n == x = True elem n (_:xs) = elem n xs -- Russ Abbott ______________________________________ Professor, Computer Science California State University, Los Angeles Google voice: 424-242-USA0 (last character is zero) blog: http://russabbott.blogspot.com/ vita: http://sites.google.com/site/russabbott/ ______________________________________

On Wed, Sep 29, 2010 at 08:17:31PM -0700, Russ Abbott wrote:
I never realized that a guard can be used as an extension of a pattern. Is this recommended coding?
Absolutely. Pattern matching and guards can and should be mixed freely.
elem n xs asks whether n is an element of xs
elem :: (Eq a) => a -> [a] -> Bool
elem _ [] = False elem n (x:_) | n == x = True elem n (_:xs) = elem n xs
Yes, this works just fine, although personally I would actually write elem without a guard: elem _ [] = False elem n (x:xs) = n == x || elem n xs This is efficient (it stops as soon as it finds a match) since || is lazy. -Brent

-----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On 9/29/10 23:17 , Russ Abbott wrote:
I never realized that a guard can be used as an extension of a pattern. Is this recommended coding? elem n xs asks whether n is an element of xs
Yep (although perhaps not ideal in this particular case). Moreover, the same things work in case statements (which function definition by patterns desugar to); IIRC "if c then t else e" is internally converted to "case () of () | c -> t | _ -> e". - -- brandon s. allbery [linux,solaris,freebsd,perl] allbery@kf8nh.com system administrator [openafs,heimdal,too many hats] allbery@ece.cmu.edu electrical and computer engineering, carnegie mellon university KF8NH -----BEGIN PGP SIGNATURE----- Version: GnuPG v2.0.10 (Darwin) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/ iEYEARECAAYFAkykEGIACgkQIn7hlCsL25WeaACguJXxy2EqO0suNG0KxRVBC2aP aAEAmwXt6sBk9Unb/hbNxPzP16v6NtFS =sVav -----END PGP SIGNATURE-----
participants (3)
-
Brandon S Allbery KF8NH
-
Brent Yorgey
-
Russ Abbott