【发布时间】:2014-11-29 03:28:14
【问题描述】:
我正在复习一些 Haskell,我正在尝试编写一个置换函数来映射 [1,2,3] -> [[1,2,3], [1,3,2], [ 2,1,3],[2,3,1],[3,1,2],[3,2,1]]。我有以下 -
permute:: [a] -> [[a]]
permute [] = []
permute list = map f list
where
f x = listProduct x (permute (exclude x list))
exclude e list1 = filter (/= e) list1
listProduct x list2 = map (x :) list2
以下是我得到的错误信息-
permutations.hs:3:20:
Couldn't match type `a' with `[a]'
`a' is a rigid type variable bound by
the type signature for permute :: [a] -> [[a]]
at permutations.hs:1:11
Expected type: a -> [a]
Actual type: a -> [[a]]
In the first argument of `map', namely `f'
In the expression: map f list
In an equation for `permute':
permute list
= map f list
where
f x = listProduct x (permute (exclude x list))
exclude e list1 = filter (/= e) list1
listProduct x list2 = map (x :) list2
Failed, modules loaded: none.
我会尝试调试,但它甚至无法编译。有什么想法吗?
【问题讨论】:
-
它在为你调试,说它期望
f是 a -> [a] 类型的函数,但得到的是 a -> [[a]] -
listProduct任何看起来都应该返回[[a]],这将使f接受参数x并返回[[a]]。也许尝试独立地试验每个功能,以确保它做你想做的事情。 -
Gilad,为什么 f 应该是 (a -> [a]) 类型?根据 map 的定义,似乎 f 有权从和映射到完全多态类型 -
map :: (a->b) -> [a] -> [b] map f [] = [] map f (x:xs) = f x : map f xs -
您应该在
f、exclude和listProduct上添加类型签名。当你有类型签名时的编译器错误会给你更多关于哪里出错的线索。 -
@TheCriticalImperitive 通常是个好主意,尽管在这种特殊情况下需要
ScopedTypeVariables扩展,实际上并没有任何帮助。
标签: debugging haskell types compiler-errors permutation