Reputation: 2721
Is it possible with pattern matching to match a range of values ? For example :
Upvotes: 6
Views: 2450
Reputation: 9566
Although @Sebastian response is correct, yes you can
{-# LANGUAGE ViewPatterns #-}
import Prelude hiding (odd)
data Peano = Zero | Succ Peano deriving Show
data PeanoInt = Neg Peano | Pos Peano deriving Show
odd :: PeanoInt -> Bool
odd (Neg Zero) = False
odd (Pos Zero) = False
odd (Neg (Succ (Succ x))) = odd $ Neg x
odd (Pos (Succ (Succ x))) = odd $ Pos x
odd _ = True
zero = Zero
one = Succ zero
two = Succ one
f :: PeanoInt -> String
f (Neg (Succ (Succ Zero))) = "-2 (then we can match all finite sets)"
f (Pos _) = "Positives"
f (odd -> True) = "Odd!"
f x = show x
main = do
print $ f (Neg two)
print $ f (Pos one)
print $ odd (Neg one)
print $ odd (Neg two)
print $ odd (Pos one)
print $ odd (Pos two)
Upvotes: 11
Reputation: 71899
No, but you can do it with guard expressions.
fn :: Int -> Int
fn i | i > 0 = (-i)
fn i | otherwise = i
Upvotes: 14