我有一個包含 LocalType 型別元素的串列(定義如下),我希望根據元素所屬的 subtptype 函式修改此串列。End 型別的元素保留在 End 型別的串列中。對于型別為 Prl(End Bar End)的元素,第一個 End 應保留在串列中,第二個 End 應附加到串列中。例如 [End, (Prl s Bar ss)] -> [End, s, ss] 例如 [End, End Bar End] -> [End, End, End] 這就是我想到的實作方式,
sepTimes :: [LocalType] -> [LocalType]
sepTimes(x:[]) = [x]
sepTimes(x:xs)
| x == End = sepTimes (x:xs)
| x == (Prl s Bar ss) = do
sepTimes (s:xs)
sepTimes (ss:xs)
正如錯誤訊息所述,我無法檢索與 Prl(End Bar End)示例中的 End 和 End 對應的元素 s 和 ss。
app\Sequents.hs:44:17: error: Variable not in scope: s :: LocalType
|
44 | | x == (Prl s Bar ss) = do
| ^
app\Sequents.hs:44:23: error:
* Variable not in scope: ss :: LocalType
* Perhaps you meant `xs' (line 42)
|
44 | | x == (Prl s Bar ss) = do
| ^^
app\Sequents.hs:45:19: error: Variable not in scope: s :: LocalType
|
45 | sepTimes (s:xs)
| ^
app\Sequents.hs:46:19: error:
* Variable not in scope: ss :: LocalType
* Perhaps you meant `xs' (line 42)
|
46 | sepTimes (ss:xs)
| ^^
以下是定義的資料型別:
data Seperator = Bar | BackAmpersand
deriving (Show, Eq, Ord, Read)
data LocalType = End
| Prl LocalType Seperator LocalType
deriving (Eq, Ord, Read)
uj5u.com熱心網友回復:
您將相等檢查與模式匹配混淆了。直觀地說,以下所有內容都應該相同:
f :: Either Int Char -> String
f (Left i) = show i
f (Right c) = [c]
f :: Either Int Char -> String
f x = case x of
Left i -> show i
Right c -> [c]
f :: Either Int Char -> String
f x
| x==Left i = show i -- what?
| x==Right c = [c]
但實際上,只有前兩個是等價的,最后一個不起作用。為什么?您不能從等式陳述句中匹配變數。這可能適用于某些等式是命題的邏輯語言,但 Haskell 的==運算子只是布林值:它需要兩個完全已知的值并告訴您它們是否完全相同。即,為了能夠寫入x==Left i,i必須已經定義了變數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/363869.html
標籤:哈斯克尔
上一篇:為什么我的Haskell函式引數必須是Bool型別?
下一篇:為這個資料型別定義一個函子實體
