我對 Haskell 很陌生,如果有任何不正確或令人困惑的語法,我深表歉意。我已經大大簡化了我想要做的事情,使其更易于理解。
首先,我有兩種用戶定義的型別:
data Foo = A String | B Int | C
type Bar = (Int, String, [Int])
我正在嘗試撰寫一個函式,以便:
myfunc :: Foo -> Bar -> Bar
--if Foo is A s,
-- increment intA
-- append s to stringA
-- return new Bar
myfunc (A s) intA stringA listA = (intA 1) stringA s listA
--if Foo is B i,
-- if listA[1]<listA[0]
-- increment intA by i
-- increment intA
-- return new Bar
-- else
-- increment intA
-- return new Bar
myfunc (B i) intA stringA (x:y:xs) = if y<x then ((intA i) 1 stringA xs) else ((intA 1) stringA xs)
--if Foo is C,
-- increment intA
-- add listA[0], listA[1]
-- prepend to listA
-- return new Bar
myfunc (C) intA stringA (top:second:xs) = (intA 1) stringA top second:xs
因此,對于每個可能的 Foo 值,myfunc 都有不同的定義。
然后我想訪問第二個引數 Bar 中的值,以回傳一個“更新”的 Bar,根據使用的 Foo 以不同的方式更新。
我目前在 myfunc (B i) 版本的 myfunc 上遇到錯誤:
Couldn't match type ‘(Int, String, [Int])’ with ‘[Bar]’
Expected type: [Bar]
Actual type: Bar
其中我解釋為編譯器期待一個串列的Bar,我不明白。
uj5u.com熱心網友回復:
甲Bar值是一個元組,而不是3個獨立的值。匹配一個現有值,并創建一個新的回傳值,就像你對任何其他 3 元組一樣。
myfunc (A s) (intA, stringA, listA) = ((intA 1), stringA s, listA)
-- etc
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/387003.html
上一篇:多個匯入行在ghci中產生錯誤
