我嘗試使用下面的代碼打印在Haskell鏈表:變量未在範圍上的錯誤使用功能衛士
data List = Node {value:: Double, next:: List}
| Empty
printList :: List -> String
printList x | x == (Node v n) = show v ++ " " ++ printList n
| otherwise = show '_'
和獲取編譯錯誤:
:load scratch.hs
[1 of 1] Compiling Main (scratch.hs, interpreted)
scratch.hs:5:26: error: Variable not in scope: v :: Double
scratch.hs:5:28: error: Variable not in scope: n :: List
scratch.hs:5:38: error: Variable not in scope: v
scratch.hs:5:53: error: Variable not in scope: n :: List
Failed, modules loaded: none.
雖然我能夠使用沒有警衛的模式匹配來做同樣的事情。
printList (Node v n) = show v ++ " " ++ printList n
printList Empty = ""
第一個代碼有什麼問題?
在'的printList(節點VN)','v'和'N'是參數,但在'x ==(Node vn)'中,它們是兩個未定義的變量。 – ForceBru
@ForceBru所以有辦法區分哪個數據構造函數x正在使用? –