为什么不能改变使用任何积分的类型?

时间:2022-12-27 21:13:32
take :: Int -> [a] -> [a]genericTake :: Integral i => i -> [a] -> [a]

I have read that the inconvenient type of take is due to historical reasons, and that changing it could cause some code to break.

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

But can't I replace take with genericTake everywhere without breaking anything? What's the problem?

但是我不能在没有破坏任何东西的情况下替换拿到genericTake吗?有什么问题?

1 个解决方案

#1


A breaking case

破案

genericTake :: Integral i => i -> [a] -> [a]genericTake n xs = take (fromIntegral n) xsclass Foo a where   bar :: a -> Stringinstance Foo Int where   bar _ = "int" foo :: String -> [a] -> [a]foo ns xs = let y = read ns                z = bar y            in take y xs

This will break for genericTake.

这将打破genericTake。

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

This is a cooked up example but you can understand some type inference occuring on the first argument of take where it is assumed that it is Int, now when you change type to Integral i => i some problems might occur as above.

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

#1


A breaking case

破案

genericTake :: Integral i => i -> [a] -> [a]genericTake n xs = take (fromIntegral n) xsclass Foo a where   bar :: a -> Stringinstance Foo Int where   bar _ = "int" foo :: String -> [a] -> [a]foo ns xs = let y = read ns                z = bar y            in take y xs

This will break for genericTake.

这将打破genericTake。

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

This is a cooked up example but you can understand some type inference occuring on the first argument of take where it is assumed that it is Int, now when you change type to Integral i => i some problems might occur as above.

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