为什么不能改变使用任何Integral的类型? [英] Why can't the type of take be changed to use any Integral?
问题描述
take :: Int - > [a] - > [a]
genericTake :: Integral i =>我 - > [a] - > [a]
我读过这个不方便的类型取
是由于历史原因,而改变它可能会导致一些代码被破坏。
但我不能替换 take
与 genericTake
无处不破?问题是什么?
打破案例
genericTake :: Integral i =>我 - > [a] - > [a]
genericTake n xs = take(fromIntegral n)xs
class Foo a where
bar :: a - >字符串
实例Foo Int其中
bar _ =int
foo :: String - > [a] - > [a]
foo ns xs = let y = read ns
z = bar y
in take y xs
这将为 genericTake
打破。
没有使用'bar'引起的(Foo i0)实例
类型变量'i0'不明确
这是一个熟悉的例子,但您可以理解某种类型的推论,它出现在第一个参数中,假设它是 Int
,现在当您将类型更改为 Integral i =>我
上面可能会出现一些问题。
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?
A breaking case
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
This will break for 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.
这篇关于为什么不能改变使用任何Integral的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!