在 Haskell 中将整数转换为 Int

发布于 2024-12-18 14:20:14 字数 473 浏览 6 评论 0原文

可能的重复:
Haskell 将整数转换为 Int?

我有一个计算birthYear 的函数,

birthYear :: Int -> Int
birthYear age = currentYear - age

currentYear :: Integral -> Integral
currentYear year = year

如何转换将 Integral 类型转换为 Int 以便birthYear 可以工作?
仅供参考,年龄固定为 Int,因为它来自 IO,我正在使用 read (age) 函数从 String 转换为 Int。

Possible Duplicate:
Haskell Convert Integer to Int?

I have a function to calculate a birthYear

birthYear :: Int -> Int
birthYear age = currentYear - age

currentYear :: Integral -> Integral
currentYear year = year

How do I cast the Integral type to an Int so birthYear can work?

FYI, age is fixed as an Int as it is coming from IO and I am using the read (age) function to convert from String to Int.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怀念你的温柔 2024-12-25 14:20:14

首先,您不能使用Integral(这是一个类型类)作为类型。您可能的意思是:

birthYear :: Int -> Int
birthYear age = currentYear - age

currentYear :: Integral a => a
currentYear = 2011

这确实有效。或者,如果您想要:

currentYear :: Integral a => a -> a
currentYear year = year

那么这也可以:

birthYear :: Int -> Int
birthYear age = (currentYear 2011) - age

IntIntegral 的实例,因此您不必“强制转换”任何内容。

First, you cannot use Integral (which is a type class) as a type. You probably meant:

birthYear :: Int -> Int
birthYear age = currentYear - age

currentYear :: Integral a => a
currentYear = 2011

And this just works. Or if you want to have:

currentYear :: Integral a => a -> a
currentYear year = year

Then this also works:

birthYear :: Int -> Int
birthYear age = (currentYear 2011) - age

Int is an instance of Integral so you do not have to "cast" anything.

一枫情书 2024-12-25 14:20:14

阅读以下内容:

http://www.haskell.org/haskellwiki/Converting_numbers

从此:

整数类型是只能包含整数而不包含整数的类型
分数。 Int(固定大小的机器整数)和Integer(任意
精度整数)是标准 Haskell 中的两种 Integral 类型
图书馆。转换类型的主力是 fromIntegral,它
会将任何整型类型转换为任何数值类型(例如 Rational、
双精度,Int16...):

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

Have a read of this:

http://www.haskell.org/haskellwiki/Converting_numbers

From this:

Integral types are ones which may only contain whole numbers and not
fractions. Int (fixed-size machine integers) and Integer (arbitrary
precision integers) are the two Integral types in the standard Haskell
libraries. The workhorse for converting types is fromIntegral, which
will convert any integral type into any numeric type (e.g.Rational,
Double, Int16...):

fromIntegral :: (Num b, Integral a) => a -> b
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文