【发布时间】:2021-01-11 06:10:18
【问题描述】:
我不明白为什么,虽然我已经声明了数据类型,但函数不接受不同的返回。我也尝试创建一个“Result”类型,但还不足以解决问题。
看看我的代码:
type Set a = [a]
type Bag a = [(a, Int)]
type Seq a = [a]
data ComposedType a = Set a | Bag [a] | Seq a deriving(Eq, Show)
data ComposedResult a = Res1 [a] | Res2 [(a, Int)]
-- This function get a list [a] and returns a list of tuples [(a, Int)]
occrs :: (Ord a) => [a] -> [(a, Int)]
occrs [] = []
occrs xs = toList (fromListWith (+) [(x, 1) | x <- xs])
--getElements :: ComposedType a -> ComposedResult a
getElements (Set a) = (Set (nub a))
getElements (Seq a) = (Seq (sort a))
getElements (Bag a) = (Bag (occrs a))
错误:
- 无法将类型 ([a], Int) 与“[a]”匹配 预期类型:ComposedType [a] 实际类型:ComposedType ([a], Int)
- 在表达式中:(Bag (occrs a)) 在“getElements”的等式中: getElements (Bag a) = (Bag (occrs a))
【问题讨论】:
-
请注意
set使用a,这意味着第一行需要ComposeType [a],而不是ComposeType a,与@987654326相同@。但现在Bag需要b ~ (a, Int),因此出现错误。 -
您将
Set用作类型别名和构造函数名称。这两个用途是不相关的:类型定义data ComposedType a = Set a | Bag [a] | Seq a根本不使用类型Set a。Bag和Seq同上。这可能不是您想要的。 -
您认为
type Set a = [a]中的Set和data ComposedType a = Set a | ...中的Set相互关联吗?如果是这样,那可能是您混淆的核心部分——它们是相同的名称,但在两个不同的名称空间中(前者的类型名称空间和后者的计算名称空间)——可能值得添加一个答案讨论这个。
标签: haskell