因使用"it"而产生的模棱两可的类型变量"a0" [英] Ambiguous type variable `a0' arising from a use of `it'

查看:95
本文介绍了因使用"it"而产生的模棱两可的类型变量"a0"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下功能以返回给定数字的因子对

I have the following function to return the Factor Pairs for a given number

factorPairs:: (RealFrac a, Floating a, Integral a) => a -> [(a, a)]
factorPairs n = map(\x -> (x, div n x)) [y | y <- [1..(ceiling $ sqrt n)], n `rem` y == 0]

当我在ghci factorPairs 18中调用该函数时,出现运行时错误

When I call the function in ghci factorPairs 18 I'm getting a run time error of

   * Ambiguous type variable `a0' arising from a use of `it'
      prevents the constraint `(Floating a0)' from being solved.
      Probable fix: use a type annotation to specify what `a0' should be.
      These potential instances exist:
        instance Floating Double -- Defined in `GHC.Float'
        instance Floating Float -- Defined in `GHC.Float'
    * In the first argument of `print', namely `it'
      In a stmt of an interactive GHCi command: print it

我可以用ghci对该函数进行硬编码

I can hard code the function in ghci

map(\x -> (x, div 18 x)) [y | y <- [1..(ceiling $ sqrt 18)], 18 `rem` y == 0] 并且没有任何问题,但我似乎无法弄清楚为什么我的功能失败了.我相信ghci试图告诉我它无法弄清楚用什么类型调用print,但是正在努力寻找解决方案.

map(\x -> (x, div 18 x)) [y | y <- [1..(ceiling $ sqrt 18)], 18 `rem` y == 0] and don't have any issues but I can't seem to figure out why my function is failing. I believe ghci is trying to tell me it can't figure out what type to call print with but am struggling to find the solution.

推荐答案

这与在Haskell中数字文字重载有关.在ghci中键入map(\x -> (x, div 18 x)) [y | y <- [1..(ceiling $ sqrt 18)], 18 `rem` y == 0]时,作为sqrt自变量的18默认为Double,其他默认为Integer s.

This has to do with the fact numeric literals are overloaded in Haskell. When you type map(\x -> (x, div 18 x)) [y | y <- [1..(ceiling $ sqrt 18)], 18 `rem` y == 0] into ghci, the 18 that is an argument to sqrt defaults to a Double and the others to Integers.

但是,当你写

factorPairs:: (RealFrac a, Floating a, Integral a) => a -> [(a, a)]
factorPairs n = map(\x -> (x, div n x)) [y | y <- [1..(ceiling $ sqrt n)], n `rem` y == 0]

您强制所有n实例只有一种类型.然后,问题就来了,就是根本没有满足所有这些约束的默认数字类型(实际上,我认为通常是数字类型),因此GHC会告诉您它尝试的可能的实例".解决方案是添加fromIntegral并放宽约束:

you force all instances of n to have only one type. Then, the problem becomes that there simply are no default number types (in fact number types in general I think) that satisfy all of these constraints, hence GHC telling you about "possible instances" it tries. The solution is to add fromIntegral and loosen the constraints:

factorPairs:: Integral a => a -> [(a, a)]
factorPairs n = map(\x -> (x, div n x)) [y | y <- [1..(ceiling $ sqrt $ fromIntegral n)], n `rem` y == 0]

这篇关于因使用"it"而产生的模棱两可的类型变量"a0"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆