10

我目前正在处理一些我没有编写的 Haskell 代码,但我已经对其进行了更改。更改后,我运行程序并收到以下错误消息:

Prelude.!!: index too large

调用!!不在我的代码中,因此如果可以避免的话,重构它比我想做的工作要多。

我想要做这样的事情:

class PrintList a where
  (!!) :: [a] -> Int -> a

instance (Show a) => PrintList a where
  l (!!) n = if n < (length l) 
             then (l Prelude.!! n)
             else error ("Index " ++ show n ++ " out of bounds in " ++ show l )

instance PrintList a where
  (!!) = Prelude.!!

即,该函数!!是为每种可能的列表类型定义的,但只要为元素类型定义了 Show 实例,它的行为就会不同。

或者,一种tryShow :: a -> Maybe String方法也可以解决问题。

有没有办法做到这一点?仅当 Show 实现不适用时,我可以强制 OverlappingInstances 使用默认实现吗?这是有保证的行为吗?

编辑:任何可以得到错误的人也可以打印类似堆栈跟踪的消息!

4

1 回答 1

8

您不需要重叠实例,只需自己使用 GHC 调试器(!!)

{-# OPTIONS -Wall -O0 #-}
module Debugger3 where

import qualified Prelude as P
import Prelude hiding ((!!))

(!!) :: [a] -> Int -> a
xs !! n =
   xs P.!! n    -- line 9

foo :: Int -> Int
foo n = [0..n] !! 3

bar :: Int -> Int
bar n = foo (n-3)

main :: IO ()
main = print (bar 4)

GHCi 会话:

> :l Debugger3
[1 of 1] Compiling Debugger3        ( Debugger3.hs, interpreted )
Ok, modules loaded: Debugger3.
*Debugger3> :break 9
Breakpoint 1 activated at Debugger3.hs:9:4-18
*Debugger3> :trace main
Stopped at Debugger3.hs:9:4-18
_result :: a = _
n :: Int = 3
xs :: [a] = _
[Debugger3.hs:9:4-18] *Debugger3> :force xs
xs = [0,1]
[Debugger3.hs:9:4-18] *Debugger3> :history
-1  : !! (Debugger3.hs:(8,1)-(9,18))
-2  : foo (Debugger3.hs:12:9-19)
-3  : foo (Debugger3.hs:12:1-19)
-4  : bar (Debugger3.hs:15:9-17)
-5  : bar (Debugger3.hs:15:1-17)
-6  : main (Debugger3.hs:18:15-19)
-7  : main (Debugger3.hs:18:8-20)
<end of history>
[Debugger3.hs:9:4-18] *Debugger3> :back
Logged breakpoint at Debugger3.hs:(8,1)-(9,18)
_result :: a
[-1: Debugger3.hs:(8,1)-(9,18)] *Debugger3> :back
Logged breakpoint at Debugger3.hs:12:9-19
_result :: Int
n :: Int
[-2: Debugger3.hs:12:9-19] *Debugger3> n
1
于 2015-11-21T08:45:07.780 回答