Matching positive integer with haskell

JeanJouX

Is it possible with pattern matching to match a range of values ? For example :

  • the whole positive integers ?
  • odd numbers ?
  • a list of values ?
josejuan

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)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related