Haskell, polyvariadic function and type inference

有些话、适合烂在心里 提交于 2019-11-30 10:49:19

The instance

instance (...) => SumRes (Int -> r) where

roughly means "here's how to define SumRes on Int -> r for any r (under certain conditions)". Compare it with

instance (...) => SumRes (a -> r) where

which means "here's how to define SumRes on a -> r for any a,r (under certain conditions)".

The main difference is that the second one states that this is the relevant instance whichever the types a,r might be. Barring some (very tricky and potentially dangerous) Haskell extension, one can not add more instances later on involving functions. Instead, the first one leaves room for new instances such as e.g.

instance (...) => SumRes (Double -> r) where ...
instance (...) => SumRes (Integer -> r) where ...
instance (...) => SumRes (Float -> r) where ...
instance (...) => SumRes (String -> r) where ... -- nonsense, but allowed

This is paired with the fact that numeric literals such as 5 are polymorphic: their type must be inferred from the context. Since later on the compiler might find e.g. a Double -> r instance and choose Double as the literal types, the compiler does not commit to the Int -> r instance, and reports the ambiguity in a type error.

Note that, using some (safe) Haskell extensions (such as TypeFamilies), it is possible to "promise" to the compiler that your Int -> r is the only one that will be declared in the whole program. This is done like this:

instance (..., a ~ Int) => SumRes (a -> r) where ...

This promises to handle all the "functional type" cases, but requires that a is actually the same type as Int.

Number literals are themselves polymorphic, rather than being of type Int

*Main> :t 1
1 :: Num a => a

Take a look what happens when we get the type signature:

*Main> :t sumOf 1 2 3
sumOf 1 2 3 :: (Num a, Num a1, SumRes (a -> a1 -> t)) => t

Notice that the type does not mention Int at all. The type checker can't figure out how to actually compute the sum because none of the defined Int instances are general enough to apply here.

If you fix the types to be Int, then you end up with

*Main> :t sumOf (1 :: Int) (2 :: Int) (3 :: Int)
sumOf (1 :: Int) (2 :: Int) (3 :: Int) :: SumRes t => t

*Main> :t sumOf (1 :: Int) (2 :: Int) (3 :: Int) :: Int
sumOf (1 :: Int) (2 :: Int) (3 :: Int) :: Int

Note that SumRes t => t is compatible with Int because we have a SumRes Int instance, but if we don't explicitly specify Int, then we have no instances general enough to apply here, because there is no general SumRes t instance.

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