Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

haskell - Is fromInteger supposed to be a ring homomorphism?

Until today I had the assumption that fromInteger in the Num class was a ring homomorphism. I had assumed this because integer is is coterminal so every ring must have a unique homomorphism from integer, so it made sense that Num, which is basically the ring class of the standard library, would include that homomorphism.

However today I was reading the laws for Num and saw that fromInteger is not required to be a homomorphism, but only required to preserve identities. So for example we can implement the Klein 4 group, and have fromInteger map 1 to multiplicative identity and everything else to the addative identity, and the result is a legal Num instance but not a homomorphism.

type Klein4
  = ( Bool
    , Bool
    )

instance
  (
  )
    => Num Klein4
  where
  ( a, b ) + ( c, d )
    = ( a /= c
      , b /= d
      )
  ( a, b ) * ( c, d )
    = ( a && b
      , b && d
      )
  negate
    = id
  fromInteger x
    = ( x == 1
      , x == 1
      )

This is a little surprising to me. So my question is why is this the case? Is the intention that fromInteger is a ring homomorphism and I'm just being pedantic, or is there a good use case where you might want to define fromInteger in a way that it is not a homomorphism (and still follows the Num laws)?

question from:https://stackoverflow.com/questions/65901824/is-frominteger-supposed-to-be-a-ring-homomorphism

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Personally, I expect fromInteger to be a ring homomorphism and would be very surprised and annoyed to find an instance that didn't have that property.

Of course, Float and Double have to be the exception to this, as to every good property. Suffice it to say that I am very surprised and annoyed by this:

> fromInteger (2^64) + fromInteger (-1) == (fromInteger (2^64-1) :: Double)
False

Most of the other proposed Num properties are broken by Float and Double, too.

I don't know of any practical types that satisfy all the current Num laws but not fromInteger x + fromInteger y == fromInteger (x+y).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...