[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Safe pattern matching
From: |
Nikita Karetnikov |
Subject: |
Safe pattern matching |
Date: |
Sat, 09 Feb 2013 04:57:26 -0500 |
Any Haskellers here?
How would you rewrite the following function in Guile?
foo :: [Int] -> String -> [Int]
foo (x:y:ys) "+" = (x + y):ys
foo (x:y:ys) "-" = (x - y):ys
foo xs num = read num:xs
*Main> foo [] "42"
[42]
*Main> foo [1,2] "42"
[42,1,2]
*Main> foo [1,2] "+"
[3]
*Main> foo [1..10] "42"
[42,1,2,3,4,5,6,7,8,9,10]
*Main> foo [1..10] "+"
[3,3,4,5,6,7,8,9,10]
It will fail if you call it like this:
*Main> foo [] "+"
[*** Exception: Prelude.read: no parse
But let's assume that it's OK.
I guess that 'match' is the answer, but I don't understand how to use
it.
pgpufEZsSNSev.pgp
Description: PGP signature
- Safe pattern matching,
Nikita Karetnikov <=