Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern Matching on Function

I have a function, dir_con :: (Int -> Dir)

I want to pattern match to find which specific constructor dir_con is. The data type is:

data Dir = Define Int
         | Equals Int 
         | Data Int  
         | LCset Int
         | NoArg Int

So, dir_con will either be Define, Equals etc. It is passed to a function and I want to pattern match like so:

case dir_con of
    NoArg -> Do something specific
    _     -> Do something for the rest

The compiler doesn't like that. Error message is Couldn't match expected type 'Int -> Dir' with actual type 'Dir'.

Surely NoArg is a constructor of type (Int -> Dir)? Does Haskell not allow this type of pattern match? I have to do this because the Dir constructors come from a map. Is there a suggestion on how I can treat NoArg differently?

like image 360
DarthGazak Avatar asked Dec 01 '25 08:12

DarthGazak


2 Answers

Two ways:

case dir_con of
    NoArg _ -> Do something specific
    _     -> Do something for the rest

You're matching the /value/ not the constructor function.

Or, usingr record syntax:

case dir_con of
    NoArg {} -> Do something specific
    _     -> Do something for the rest

which is good hygiene, as it is neutral with respect to the number of fields.

like image 182
Don Stewart Avatar answered Dec 03 '25 00:12

Don Stewart


You cannot pattern match on functions. A value of type Dir is built by applying one of several constructors, but dir_con is a function of type Int -> Dir.

You probably want to apply the function before pattern matching:

case dir_con 7 of  -- `7` is just an arbitrary value I'm passing
  NoArg _ -> ...
  _       -> ...

In addition, you have to match on the argument of the NoArg constructor as well, or else you'll get another type error after adding the argument to dir_con.

In your concrete situation, you'll most likely not want to pass a literal integer, but perhaps an argument you're getting from elsewhere:

myfun n = ... case dir_con n of
                NoArg _ -> ...
                _       -> ...
like image 44
kosmikus Avatar answered Dec 02 '25 23:12

kosmikus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!