首页 > 解决方案 > 我将集合转换为列表的 Haskell 程序出现错误

问题描述

我是一个初学者程序员,我已经为我的集合创建了一个数据类型。然后我编写了一个函数将它们转换为列表,但我不断收到以下表达式错误消息:

toList 3 :-: 4 :-: 5 :-: Empty 
Non type-variable argument in the constraint: Num (Set a)
      (Use FlexibleContexts to permit this)

When checking the inferred type
        it :: forall a. (Num (Set a), Num [a]) => Set [a]

这是我的代码:

infixr 5 :-:
data Set a = Empty | a :-: (Set a) deriving (Show, Read, Eq, Ord)

toList :: Set a -> [a]
toList Empty = []
toList (x :-: xs) =  x : toList xs

标签: listhaskelltypesset

解决方案


问题是它toList 3 :-: 4 :-: 5 :-: Empty被解析为(toList 3) :-: 4 :-: 5 :-: Empty,但你实际上想要toList (3 :-: 4 :-: 5 :-: Empty)。要使其工作,您需要编写后者,或使用$,如下所示:toList $ 3 :-: 4 :-: 5 :-: Empty.


推荐阅读