![](/img/trans.png)
[英]Issues with pattern matching and case expression over Data.Typeable.TypeRep
[英]'pattern matching' on Typeable types
例如,假設我們有以下數據結構:
data Foo = Bool Bool | Int Int | Double Double
現在,有沒有更簡單的方法來做到這一點:
foo :: Typeable a => a -> Foo
foo x = maybe (error "i dunno") id $
liftM Bool (cast x) `mplus`
liftM Int (cast x) `mplus`
liftM Double (cast x)
有人想過為Typeable類型的模式匹配制定語法嗎?
使用typeOf
和守衛:
foo x
| tx == typeOf "str" = "string"
| tx == typeOf True = "bool"
| otherwise = "i dunno"
where tx = typeOf x
您可以在此處使用視圖模式,它們是非常方便的擴展。
{-# LANGUAGE ViewPatterns #-}
import Data.Data
data Foo = Bool Bool | Int Int | Double Double
deriving (Show)
foo :: Typeable a => a -> Foo
foo (cast -> Just x) = Int x
foo (cast -> Just x) = Bool x
foo (cast -> Just x) = Double x
foo _ = error "i dunno"
結果:
*Main> :l foo_typeable.hs [1 of 1] Compiling Main ( foo_typeable.hs, interpreted ) Ok, modules loaded: Main. *Main> foo "123" *** Exception: i dunno *Main> foo 1 *** Exception: i dunno *Main> foo (1 :: Int) Int 1 *Main> foo (1 :: Integer) *** Exception: i dunno *Main> foo (1 :: Double) Double 1.0
此版本不限於Bool
、 Int
或Double
,但String
以[Char]
的形式出現。
foo :: Typeable a => a -> String
foo = show . typeOf
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.