我有一个代数数据类型,例如:
data Toll = Vok Int Bool | Bok Int | Cokd String Char
还有另一个函数
getVal :: Int -> Toll
getVal 1 = Cokd "hello" 'c'
getVal _ = Bok 12
我想在某个函数中调用 getVal
并提取 Cokd
的参数(如果答案是 Cokd
类型)(也许使用模式匹配)。
我可以这样做吗:
hello :: Int -> Bool
hello x = if st == "hell" then True else False
where (Cokd st ch) = getVal x
我无法使用 monad。
如何做到这一点?
最佳答案
您可以使用case
对getVal
的结果进行模式匹配:
data Toll = Vok Int Bool | Bok Int | Cokd String Char
getVal :: Int -> Toll
getVal 1 = Cokd "hello" 'c'
getVal _ = Bok 12
hello :: Int -> Bool
hello x =
case getVal x of
Cokd st ch ->
st == "hell"
_ -> False
或者创建一个单独的函数并模式匹配参数:
hello :: Int -> Bool
hello =
helloToll . getVal
where
helloToll (Cokd st ch) = st == "hell"
helloToll _ = False
<小时/>
您在问题中提供的示例可以编译(只需少量修改),但当您尝试使用 2
调用 hello
时,它将引发运行时异常(或与 1
不同的任何其他值,在这种情况下 getValue
返回 Bok 12
,因此 (Cokd st ch) = getVal x
模式匹配失败)。
关于Haskell 对函数结果进行模式匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46397583/