Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern match in binding of lambda?

In Haskell, I often do something like this:

f $ \x -> case x of
            A a1 a2 -> ...
            B b1 b2 -> ...
            C c1 c2 -> ...

But I don't want x, I just want to deconstruct it.

In Standard ML I can do something like this:

f (fn A(a1,a2) => ...
    | B(b1,b2) => ...
    | C(c1,c2) => ...)

Is there a way to do this in Haskell or with any GHC extensions?

like image 794
og_loc Avatar asked Feb 23 '15 20:02

og_loc


People also ask

What is pattern matching in ML?

A special feature of languages in the ML family is pattern matching. It allows simple access to the components of complex data structures. A function definition most often corresponds to pattern matching over one of its parameters, allowing the function to be defined by cases.

Why ++ is not allowed in pattern matching?

You can only pattern-match on data constructors, and ++ is a function, not a data constructor. Data constructors are persistent; a value like 'c':[] cannot be simplified further, because it is a fundamental value of type [Char] .


1 Answers

You can use the LambdaCase language extension and perform

{-# LANGUAGE LambdaCase #-}
... 
f $ \case 
     A a1 a2 ->
...

as per your example.

You can read more about it in GHC's documentation

like image 118
Arnon Avatar answered Oct 08 '22 23:10

Arnon