Why can't I map a pattern in a type family?

Consider the following code:

{-# LANGUAGE TypeFamilies #-}

data Twothings a b = Twothings a b

type family Leftthing a where
  Leftthing (Twothings a b) = Leftthing a
  Leftthing a = a

leftthing :: a -> Leftthing a
leftthing (Twothings a b) = leftthing a
leftthing b = b

It does not compile with the following error:

Couldn't match expected type β€˜a’
                  with actual type β€˜Twothings a0 t0’
      β€˜a’ is a rigid type variable bound by
        the type signature for:
          leftthing :: forall a. a -> Leftthing a

He complains about the string leftthing (Twothings a b) = leftthing a. If I understand correctly, it cannot unify a type variable in a type asignature with a constructor type Twothings. Well, that seems to make sense. But then, how can I define a function with type families in a type signature?

+4
source share
1 answer

When you announce

leftthing :: a -> Leftthing a

you say that the caller leftthingchooses that a.

When you write

leftthing (Twothings a b) = leftthing a

You assume that you have selected a type Twothings, and, as it is not necessary, your program is rejected.

, , , Twothings, ! , .

. leftthing leftthing.

type family Leftthing a where
  Leftthing (Twothings a b) = Leftthing{-you forgot the recursion!-} a
  Leftthing a = a

GADT Twothing ness.

data IsItTwothings :: * -> * where
  YesItIs   :: IsItTwothings a -> IsItTwothings (Twothings a b)
  NoItIsn't :: Leftthing a ~ a => IsItTwothings a
            -- ^^^^^^^^^^^^^^^ this constraint will hold for any type
            -- which is *definitely not* a Twothings type

:

leftthing :: IsItTwothings a -> a -> Leftthing a
leftthing (YesItIs r) (Twothings a b) = leftthing r a
leftthing NoItIsn't   b               = b

, - Twothings es . , .

> leftthing (YesItIs (YesItIs NoItIsn't)) (Twothings (Twothings True 11) (Twothings "strange" [42]))
True

, , . , ( , ). ( ). , .

, ,

leftthing :: pi a. a -> Leftthing a

pi - , , , . , , .

+10

Source: https://habr.com/ru/post/1685346/


All Articles