Mapping a positive integer to haskell

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

  • positive integers?
  • odd numbers?
  • list of values?
+3


source to share


2 answers


While @ Sebastian's answer 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)

      

+7


source


No, but you can do it with defensive expressions.



fn :: Int -> Int
fn i | i > 0 = (-i)
fn i | otherwise = i

      

+10


source







All Articles