【发布时间】:2022-01-19 02:33:18
【问题描述】:
我对 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 的列表,我不明白。
【问题讨论】:
标签: haskell types parameters pattern-matching