Alex K.
Alex K.

Reputation: 93

How to get a constructor as a function from the (G)ADT argument in Haskell?

How to get a constructor as a function from the (G)ADT argument in Haskell? Is it possible to do something like this?

data  Ex1 =  C1 Int | C2 Int -- | ..... 
           | C3

fun :: Ex1 -> Ex1
fun C3    = C3
fun (c i) = c $ i^2

It is not appropriate for me to.

fun (C1 i) = C1 $ i^2
fun (C2 i) = C2 $ i^2

Upvotes: 0

Views: 96

Answers (1)

Sibi
Sibi

Reputation: 48766

If you are ok with changing the type of Ex1 then:

{-# LANGUAGE DeriveFunctor #-}

data  Ex1 a =  C1 a | C2 a
            | C3 deriving (Show, Functor)

fun :: Ex1 Int -> Ex1 Int
fun y = fmap (\x -> x^2) y

Demo in ghci:

λ> fun $ C1 3
C1 9
λ> fun $ C2 3
C2 9
λ> fun C3
C3

Upvotes: 6

Related Questions