首页 > 解决方案 > Haskell "With" 数据类型

问题描述

我正在 Haskell 中创建一个函数,它将为我提供字符串中字符的频率。

输入:

frequencies "hello world"

不想要的输出:

[1 :- ’ ’,1 :- ’d’,1 :- ’e’,1 :- ’h’,3 :- ’l’,2 :- ’o’,1 :- ’r’,1 :- ’w’]

我的代码:

frequencies  ::  (Ord char) => [char] -> [With Int char]
frequencies a = map (buildWith) (group (sort (head (tails a))))

buildWith :: [char] -> With Int char
buildWith a = With (length a) (head a)

现在我无法让它工作,主要是因为我找不到有关“With”数据类型的信息。我不知道我是否正确使用它。这是 Haskell 解释器返回的错误:

[3 of 3] Compiling Huffman          ( C:\\Huffman.hs, interpreted )

C:\\Huffman.hs:17:16: error:
    Data constructor not in scope: With :: Int -> char -> With Int char
   |
17 | buildWith a = (With (length a) (head a))
   |                ^^^^
Failed, two modules loaded.

我很好奇我做错了什么以及如何解决它。提前致谢!

编辑:对于那些对 With 数据类型感兴趣的人:

infix 1 :-
data With a b  =  a :- b
  deriving (Show)

satellite :: With a b -> b
satellite (_ :- b)  =  b

instance (Eq a) => Eq (With a b) where
  (a :- _) == (b :- _)  =  a == b
instance (Ord a) => Ord (With a b) where
  (a :- _) <= (b :- _)  =  a <= b

标签: haskell

解决方案


推荐阅读