Haskell错误:无法匹配期望的类型'Integer'对比推断类型`Int' [英] Haskell Error: Couldn't match expected type `Integer' against inferred type `Int'

查看:78
本文介绍了Haskell错误:无法匹配期望的类型'Integer'对比推断类型`Int'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个haskell函数来计算有限Ints列表的大小。我需要输出类型为Integer,因为该值实际上会大于Int的最大范围(如果输出类型为Int,结果将为-1)

I have a haskell function that that calculates the size of the list of finite Ints. I need the output type to be an Integer because the value will actually be larger than the maximum bound of Int (the result will be -1 to be exact if the output type is an Int)

size :: a -> Integer
size a =  (maxBound::Int) - (minBound::Int)

我理解Ints(有界)和Integers(无界)之间的区别,但我想从Int构造一个Integer。我想知道是否有像fromInteger这样的函数,这将允许我将Int转换为Integer类型。

I understand the difference between Ints (bounded) and Integers (unbounded) but I'd like to make an Integer from an Int. I was wondering if there was a function like fromInteger, that will allow me to convert an Int to an Integer type.

推荐答案

您需要将值转换为整数,这可以通过fromIntegral函数完成(对Haskell进行数值转换):

You'll need to convert the values to Integers, which can be done by the fromIntegral function (numeric casting for Haskell):

fromIntegral :: (Integral a, Num b) => a -> b

它将Integral类中的任何类型转换为(更大)Num类中的任何类型。例如

It converts any type in the Integral class to any type in the (larger) Num class. E.g.

fromIntegral (maxBound::Int) - fromIntegral (minBound::Int)

然而,我不太相信你正在采取的方法 - 它看起来非常脆弱。在存在允许环绕的类型的情况下的行为是相当可疑的。

However, I would not really trust the approach you're taking -- it seems very fragile. The behaviour in the presence of types that admit wraparound is pretty suspect.

你真正的意思是:有限Ints列表的大小。这种意义上的大小,如果不是列表的长度?

What do you really mean by: "the size of the list of finite Ints". What is the size in this sense, if it isn't the length of the list?

这篇关于Haskell错误:无法匹配期望的类型'Integer'对比推断类型`Int'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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