匹配正整数与haskell

时间:2015-06-05 09:07:18

标签: haskell pattern-matching ghc

模式匹配是否可以匹配一系列值?例如:

  • 整个正整数?
  • 奇数?
  • 值列表?

2 个答案:

答案 0 :(得分:11)

不,但您可以使用保护表达式。

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

答案 1 :(得分:8)

虽然@Sebastian的回答是正确的,你可以

{-# 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)