I want a function like following, is this possible? in fact, I don't know if the type Pattern exists.
fun1 a :: Pattern a -> a -> Bool
fun1 pattern a = case a of
pattern -> True
_ -> False
I don't think this is possible in Haskell.
However, in your case, the pattern is effectively just a function of type a -> Bool
. So instead of accepting a pattern, accept any function from a
to Bool
. You example is equivalent to applying a function a -> Bool
on an a
.
Now, if you wanted to do something more general, like being able to use the matched symbols from the pattern in the body of fun1
, you would not be able to do it with a function. However, I doubt this is possible with Haskell at all--it would require weird extensions to the type system to make any sense. Pattern matching in Haskell is not a first-class citizen at all, so you can't really pass patterns around like that.
If you want this kind of behavior, check out the book Pattern Calculus where the author develops and formalizes a language with more general pattern-matching features than Haskell. It makes patterns a first-class citizen, unlike Haskell. I haven't actually finished this book yet, but I'm pretty sure that code like that is exactly what you would be able to write, among other things.
The author built a language around his ideas about pattern matching called bondi; it's probably also worth checking out, especially if you don't want to bother with the book. I don't know if it's ready for practical use, but it's certainly interesting.
Check out the Functional Pearl, Type Safe Pattern Combinators. A bit of Googling shows that there is a Hackage package based on it as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With