Why is this implementation invalid?

末鹿安然 提交于 2019-12-23 10:37:10

问题


Let's say I have the following type signature:

someFunction :: (Eq a, Eq b) => a -> b

With implementation:

someFunction x = (2 :: Int)

(Don't look in to it too far, it's just an example).

My understanding of the signature is that "someFunction takes an argument that is an instance of the Eq typeclass, and returns a value (that can be of a different type) that is an instance of the Eq typeclass". Int is an instance of Eq, so why does GHC get upset about this implementation?

The error makes it obvious enough:

Couldn't match expected type ‘b’ with actual type ‘Int’
     ‘b’ is a rigid type variable bound by
       the type signature for:
         someFunction :: forall a b. (Eq a, Eq b) => a -> b

I guess what I don't understand is the requirement that it work "forall" b. Any code using this function should only rely on the fact that b is an instance of Eq, right? In my head, the implementation does match the signature. What about my implementation is breaking the expectations of this signature?


回答1:


No, your type signature, which is actually

forall a b. (Eq a, Eq b) => a -> b

means that your function must be callable with any types a and b, as determined by the call site, as long as both are instances of Eq.

It is not your function that decides what type to return. It's your function's use that determines that.

So you should be able to write

    let { i :: Int; i = 1;
          n :: Integer; y :: Double;
          n = foo i;   -- foo :: Int -> Integer
          y = foo i    -- foo :: Int -> Double
        }

and as you can see, the only implementation for your function is no implementation:

foo _ = x where {x = x}

because you have no way to produce a value of any type that's demanded of you. That type can be anything, and you have no way of knowing anything about it.


By the way other typeclasses might actually allow you to define something here, like

foo :: (Enum a, Enum b, Bounded a, Bounded b) => a -> b 
foo a = snd . last $ zip [minBound .. a] (cycle [minBound ..])

I'm not saying it's a sensible definition, just that it is possible:

> foo () :: Bool
False

> foo True :: Int
-9223372036854775807

> foo (0 :: Int) :: Bool
Interrupted.

It is probably a common misconception for programmers coming from the more usual languages to think that foo :: (Eq a) => a means "I get to define foo to return any type I want, as long as it is in Eq". It doesn't. :)



来源:https://stackoverflow.com/questions/52924772/why-is-this-implementation-invalid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!