gpt4 book ai didi

haskell "Non-Exhaustive pattern exception"

转载 作者:行者123 更新时间:2023-12-04 22:07:47 26 4
gpt4 key购买 nike

下面的代码在函数 asd 中产生了一个“非穷举模式”

data Token = TokenPlus
| TokenMinus
| TokenMal
| TokenGeteilt
| TokenKlammerAuf
| TokenKlammerZu
| TokenInt Int
deriving(Eq,Show)
asd (x:xs) = if x == '+' then (x, TokenPlus): (asd xs)
else (x, TokenInt 1): (asd xs)

假设我想捕捉这种错误,我会使用 catch (asd "my_string") my_handler_function .到这里还好,但是类型是什么 ":t 'non-exhaustive pattern' "由 ?

最佳答案

(x:xs)不匹配 [] ,但因为它将匹配 '1':[] ([1] 的无糖版本),当你处理每个元素时,你会得到模式匹配失败,因为你没有告诉程序最后要做什么(即停止)。绝对没有理由让这种情况发生,只需为空列表添加一个基本情况:

asd [] = []

顺便说一句,这只是 map的手卷版.可以写成
asd xs = map (\x -> if x == '+' then (x, TokenPlus) else (x, TokenInt 1)) xs

关于 haskell "Non-Exhaustive pattern exception",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6088341/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com