2014-10-07 67 views
0

我的功能:故障基本情況哈斯克爾

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 

我想第1功能檢查就INTS和空話的列表,只有返回剛纔值。而第二個函數只返回Nothings。

他們蒐集精而不basecase其中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. 

我可以把那裏,而不是[],使這個編譯?我沒有想法。

回答

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 
+0

神感謝,emberrasing! – Rewbert 2014-10-07 15:13:13

+1

@Rewbert另請注意,'x == True'與'x'完全相同。你應該只有'| isNothing r = r:checkBlock rs',對於下一行也是類似的。 – bheklilr 2014-10-07 15:14:09

+1

'checkBlock = filter isNothing' – 2014-10-07 15:18:59

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 istaed的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