我不明白:来自整合 [英] I don't understand :t for fromIntegral

查看:81
本文介绍了我不明白:来自整合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LYAH 描述 fromIntegral as:


从它的类型签名中我们可以看到它需要一个整数并将其转换为一个更一般的数字。


我不明白这个函数是如何工作的,或者,为什么需要与翻译人员一起玩耍。

  fromInteral 4 + 3.2 
7.2
4 + 3.2
7.2 - 似乎有效正好?!
fromInteral 6
6
fromInteral 6.2
- 引发错误

:t fromInteral
fromInteral ::(Integral a,Num b )=> a - > b - 这是否意味着需要1个参数或2个?


解决方案

  fromIntegral: :(积分a,数字b)=> a  - > b 

需要一个参数。应该将 => 看作具有通用量化的逻辑蕴涵:


所有类型 a b


如果 a 集成 b Num



然后 fromInteral 可以使用 a 并生成 b


此函数将类型 a (它是 Integral 类型)到 b 类型(它是更一般的 Num 类的一个实例)。例如。你不能将整数 1 添加到Haskell中的float 2 ,而无需转换前者:

  Prelude> (1 :: Int)+(2 :: Float)

< interactive>:10:15:
无法与实际类型为'Float'的预期类型'Int'匹配b $ b在`(+)'的第二个参数中,即`(2 :: Float)'
在表达式中:(1 :: Int)+(2 :: Float)
在等式:it =(1 :: Int)+(2 :: Float)
Prelude> fromIntegral(1 :: Int)+(2 :: Float)
3.0


LYAH describes fromIntegral as:

From its type signature we see that it takes an integral number and turns it into a more general number. That's useful when you want integral and floating point types to work together nicely.

I don't understand how this function works at all or why it is needed from playing around with the interpreter.

fromIntegral 4 + 3.2
7.2
4 + 3.2
7.2 -- seems to work just fine?!
fromIntegral 6
6
fromIntegral 6.2
-- raises an error

:t fromIntegral
fromIntegral :: (Integral a, Num b) => a -> b -- does this mean it takes 1 arg or 2?

解决方案

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

takes one arg. The => should be read as a logical implication with universal quantification:

for all types a and b,

if a is an instance of Integral and b is an instance of Num,

then fromIntegral can take an a and produce a b.

This function converts a value of type a (which is an Integral type) to the b type (which is an instance of the more general Num class). E.g. you cannot add the integer 1 to the float 2 in Haskell without converting the former:

Prelude> (1 :: Int) + (2 :: Float)

<interactive>:10:15:
    Couldn't match expected type `Int' with actual type `Float'
    In the second argument of `(+)', namely `(2 :: Float)'
    In the expression: (1 :: Int) + (2 :: Float)
    In an equation for `it': it = (1 :: Int) + (2 :: Float)
Prelude> fromIntegral (1 :: Int) + (2 :: Float)
3.0

这篇关于我不明白:来自整合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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