gpt4 book ai didi

haskell - 我不明白 :t for fromIntegral

转载 作者:行者123 更新时间:2023-12-02 12:13:26 24 4
gpt4 key购买 nike

LYAHfromIntegral 描述为:

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.

我根本不明白这个函数是如何工作的,也不明白为什么需要它来玩解释器。

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

采用一个参数。 =>应理解为具有普遍量化的逻辑蕴涵:

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.

该函数转换 a 类型的值(这是一个 Integral 类型)到 b type(这是更通用的 Num 类的实例)。例如。您不能添加整数 1到 float 2在 Haskell 中,无需转换前者:

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

关于haskell - 我不明白 :t for fromIntegral,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23168462/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com