我的职能:
type Block = [Maybe Int]
checkBlock' :: Block -> Block
checkBlock' (r:rs)
| r == [] = []
| isJust r == True = r:checkBlock' rs
| isNothing r == True = checkBlock' rs
checkBlock :: Block -> Block
checkBlock (r:rs)
| r == [] = []
| isNothing r == True = r:checkBlock rs
| isJust r == True = checkBlock rs
我想首先检查Just Ints和Nothings的列表,并仅返回Just值。而第二个功能只返回Nothings。
他们在没有r == [] = []
的基础的情况下编译正常,但是我得到了错误:
Sudoku.hs:104:12:
Couldn't match expected type `Maybe Int' with actual type `[t0]'
In the second argument of `(==)', namely `[]'
In the expression: r == []
In a stmt of a pattern guard for
an equation for checkBlock':
r == []
Failed, modules loaded: none.
我可以放在那里而不是[]进行编译?我有很多想法。
答案 0 :(得分:2)
你应该在这里使用模式匹配,而不是守卫:
checkBlock :: Block -> Block
checkBlock [] = []
checkBlock (r:rs)
| isNothing r == True = r:checkBlock rs
| isJust r == True = checkBlock rs
或者,最好是:
checkBlock :: Block -> Block
checkBlock [] = []
checkBlock (Nothing : rs) = Nothing : checkBlock rs
checkBlock (Just _ : rs) = checkBlock rs
答案 1 :(得分:1)
您无法将r
与空列表进行比较,您只能比较整个列表。
作为替代方案,你可以写
checkBlock :: Block -> Block
checkBlock rs
| rs == [] = []
| isNothing (head rs) == True = (head rs):checkBlock (tail rs)
| isJust (head rs) == True = checkBlock (tail rs)
其次,警卫已经使用Bool
,因此== True
是不必要的。顺便说一下,尝试使用null rs
rs == []
checkBlock :: Block -> Block
checkBlock rs
| null rs = []
| isNothing (head rs) = (head rs):checkBlock (tail rs)
| isJust (head rs) = checkBlock (tail rs)
但这看起来有点难看,让我们使用模式匹配:
checkBlock :: Block -> Block
checkBlock [] = []
checkBlock (r:rs)
| isNothing r = r:checkBlock rs
| isJust r = checkBlock rs