9
take :: Int -> [a] -> [a]
genericTake :: Integral i => i -> [a] -> [a]

我读过不方便的类型take是由于历史原因,并且更改它可能会导致某些代码中断。

但是我不能在不破坏任何东西的情况下替换任何地方吗takegenericTake有什么问题?

4

1 回答 1

10

破案

genericTake :: Integral i => i -> [a] -> [a]
genericTake n xs = take (fromIntegral n) xs

class Foo a where
   bar :: a -> String

instance Foo Int where
   bar _ = "int" 

foo :: String -> [a] -> [a]
foo ns xs = let y = read ns
                z = bar y
            in take y xs

这将打破genericTake.

No instance for (Foo i0) arising from a use of `bar'
    The type variable `i0' is ambiguous

这是一个熟透的例子,但您可以理解在假设它是 take 的第一个参数上发生的一些类型推断Int,现在当您将类型更改为Integral i => i某些问题时,可能会出现上述问题。

于 2013-06-23T16:39:17.230 回答