简体   繁体   中英

Could not match polymorphic type in haskell

I am not sure why k4 below does not work, when k3 does, its enough polymorphic. The error in ghci is

 • Couldn't match type 'K' a0 a0' with 'End K'' Expected type: K' a0 a0 -> K'' aa 
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE GADTs #-}
#!/usr/bin/env stack
-- stack --install-ghc --resolver lts-8.21 runghc --package http-conduit --package lens
{-# LANGUAGE ExistentialQuantification, RankNTypes #-}

module YonedaLan where

type End g = forall a. g a a 

data K'  b c = K'
data K'' b c = K''

k1 :: () -> End K'
k1 x = K'

k2 :: End K' -> End K''
k2 x = case x of (K') -> K''

k3 :: () -> End K''
k3 x = k2 ( k1 x)

k4 :: () -> End K''
k4 = k2 . k1

Beside not writing point free style, is there some best practice for dealing with this ?

The problem is that the GHC type system will never instantiate a type variable to a polymorphic type. Doing that would require impredicativity in the type system.

In your concrete example, we have

(.) :: (b->c) -> (a->b) -> (a->c)

and, to type check k2 . k1 k2 . k1 we would need to instantiate b ~ End K' which is a polymorphic type.

A typical workaround would be to make End K' into a monomorphic type which wraps a polymorphic type. Eg

newtype End g = End { unEnd :: forall a. g a a }

The price to pay is to explicitly wrap / unwrap values of type End g at every usage. This can also be mitigated exploiting GHC's "safe coercions".

Note that some other languages (like Agda, Coq, Idris) would handle your code (suitably translated) just fine, since they have an impredicative type system. However, their inference machinery are different from Haskell -- impredicativity makes it far harder. Sometimes, if not often, the type inference engine can't find the implicit type arguments, and types have to be explicitly provided.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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