如何在haskell中对两个参数进行模式匹配



我是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列表,但我不理解。

Bar值是单个元组,而不是3个单独的值。匹配一个现有的值,并创建一个新的值进行返回,就像处理任何其他三元组一样。

myfunc (A s) (intA, stringA, listA) = ((intA + 1), stringA++s, listA)
-- etc

最新更新