与Show函数实例相关的错误

时间:2011-04-16 15:58:17

标签: haskell types show typeclass

我有以下代码,我想我错过了一些东西:

bruteSolveWithStartAndEnd :: Node -> Node -> [Node] -> [(Float, [Node])] -> [(Float, [Node])]
bruteSolveWithStartAndEnd st en mp r
           | length mp - 1 == length (snd ( head r)) = sortBy (comparing fst) $ map (\x -> (fst x + (distanceBetweenTwoNodes en $ last $ snd x), snd x ++ [en])) r
           | otherwise = bruteSolveWithStartAndEnd st en mp $ nextStepsForMany r $ filter (/= en) mp

bruteSolve :: [Node] -> [(Float, [Node])] -> [(Float, [Node])]
bruteSolve mp [] = bruteSolve mp $ map (\l -> (0, [l])) mp
bruteSolve mp r
           | length mp == length(snd (head r)) = sortBy (comparing fst) $ r
           | otherwise = bruteSolve mp $ nextStepsForMany r mp

nextSteps :: (Float, [Node]) -> [Node] -> [(Float, [Node])]
nextSteps r n = map (\l -> ((fst r) + (distanceBetweenTwoNodes l $ last $ snd r), snd r ++ [l])) [ nn | nn <- n, nn `notElem` (snd r)]

nextStepsForMany :: [(Float, [Node])] -> [Node] -> [(Float, [Node])]
nextStepsForMany ar n = concat $ map (\l -> nextSteps l n) ar

代码本身有效。但奇怪的是,虽然函数bruteSolve和bruteSolveWithStartAndEnd具有相同的“结果”类型,但是bruteSolveWithStartAndEnd的结果不能在GHSi中打印,而bruteSolve的结果可以:

*> bruteSolve [(Node 0 1), (Node 2 3), (Node 4 5)] []
[(5.656854,[Node {x = 0, y = 1},Node {x = 2, y = 3},Node {x = 4, y = 5}]),(5.656854,[Node {x = 4, y = 5},Node {x = 2, y = 3},Node {x = 0, y = 1}]),(8.485281,[Node {x = 0, y = 1},Node {x = 4, y = 5},Node {x = 2, y = 3}]),(8.485281,[Node {x = 2, y = 3},Node {x = 0, y = 1},Node {x = 4, y = 5}]),(8.485281,[Node {x = 2, y = 3},Node {x = 4, y = 5},Node {x = 0, y = 1}]),(8.485281,[Node {x = 4, y = 5},Node {x = 0, y = 1},Node {x = 2, y = 3}])] 


*> bruteSolveWithStartAndEnd (Node 0 0) (Node 5 5) [Node 0 0, Node 1 1, Node 2 2, Node 3 3, Node 4 4, Node 5 5]

<interactive>:1:1:
    No instance for (Show ([(Float, [Node])] -> [(Float, [Node])]))
      arising from a use of `print'
    Possible fix:
      add an instance declaration for
      (Show ([(Float, [Node])] -> [(Float, [Node])]))
    In a stmt of an interactive GHCi command: print it

我做错了什么?我改变了一些东西(不记得是什么),从那以后出现了这个错误。根据我的理解(Haskell的第一天),print函数将检查[..]是否导出Show然后递归所有内部元素(在本例中为list-&gt; tuple-&gt;(Float&amp; Node)) ...无论如何,因为“结果”声明是相同的,为什么会出现这种差异?

干杯!

2 个答案:

答案 0 :(得分:3)

(Show ([(Float, [Node])] -> [(Float, [Node])]))的任何实例都没有说您正在尝试打印功能。那可能不是你想要做的......你忘记了对bruteSolveWithStartAndEnd的争论吗?

答案 1 :(得分:2)

你没有向bruteSolveWithStartAndEnd提供足够的论据。像

这样的查询
bruteSolveWithStartAndEnd (Node 0 0) (Node 5 5) [Node 0 0, Node 1 1, Node 2 2, Node 3 3, Node 4 4, Node 5 5] []

应该有用。