I have a type with several constructors wrapping another type; let's use the example below (in practice I have many constructors):
data New a = A a | B a
Now I need a function fun :: (a -> b) -> New a -> b
which applies the first argument f :: a -> b
to the value wrapped in x :: New a
. I can do this with pattern matching:
fun f (A v) = f v
fun f (B v) = f v
This is not elegant at all! It seems like I should be able to do something like fun f (_ v) = f v
instead, but GHC gives me Parse error in pattern
.
Similarly, I want a function con :: New a -> (a -> New a)
which returns the constructor. Again, I can pattern match:
con (A _) = A
con (B _) = B
The obvious pattern to unite these is con (x _) = x
, but this throws another Parse error in pattern: x
.
Questions:
- Is there a shorter, more elegant way of defining
fun
andcon
by uniting cases? - Why GHC opposed to these patterns?
- Am I trying to do something taboo here?
Note: I have formal training in mathematics, but I am self-taught at programming. I am also somewhat new to haskell
--sorry if this question has an obvious, trivial answer. I've tried quite a lot of googling, but I haven't had any success.