简体   繁体   English

Haskell:Num如何举行?

[英]Haskell: How is Num held?

In the following example: 在以下示例中:

> let sum::Num a=> a->a->a; sum a b = a +b
> let partialSum = sum 1
> partialSum 2.0
3.0

In step let partialSum = sum 1 it would appear that a is interpreted as Integer but I suppose Haskell delays this until it can figure out the type (and consequently which typeclass instance to use) until the whole expression is built. 在步骤中, let partialSum = sum 1 ,似乎a被解释为Integer,但我认为Haskell将其延迟,直到它可以计算出类型(以及因此使用哪个类型类实例),直到构建整个表达式为止。 We can interpret this because the ultimate result is Fractional (3.0) 我们可以解释这个,因为最终的结果是分数(3.0)

But at this point let partialSum = sum 1 GHCI has to hold 1 in memory, I was wondering what does it hold it as? 但是在这一点上let partialSum = sum 1 GHCI必须在内存中保持1 ,我想知道它是什么呢?

The answer can be broken down in two components: 答案可以分为两个部分:

  • Typeclass constraints get elaborated as records and they're automatically passed around whenever needed. 类型类约束被详细描述为记录,并且它们会在需要时自动传递。

  • A numeric literal n is translated to fromInteger n 数字文字n被转换为fromInteger n

So 所以

sum :: Num a => a -> a -> a
sum a b = a + b

would become: 会成为:

sum' :: RecordNum a -> a -> a -> a
sum' dict a b = (plus dict) a b

where 哪里

data RecordNum a = RecordNum
    { plus :: a -> a -> a
    ; mult :: a -> a -> a
    (...)
    ; fromInteger :: Integer -> a
    }

and then 接着

partialSum :: Num a => a -> a
partialSum = sum 1

becomes

partialSum' :: RecordNum a -> a -> a
partialSum' dict = sum' dict (fromInteger dict 1)

But at this point let partialSum = sum 1 GHCi has to hold 1 in memory 但是在这一点上, let partialSum = sum 1 GHCi必须在内存中保持1

Sure, but remember that Haskell number literals are overloaded. 当然,但请记住,Haskell数字文字已经过载。 In this case, 1 gets stored as fromInteger (1 :: Integer) :: Num a => a . 在这种情况下, 1被存储为fromInteger (1 :: Integer) :: Num a => a partialSum holds onto this until it knows what a should be. partialSum持有到这个直到它知道什么a应该的。 GHCi holds onto only 1 the Integer . GHCi仅保留1 Integer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM