Home > Software engineering >  Pattern matching haskell
Pattern matching haskell

Time:10-22

i would be really glad, if someone could get me a hint how pattern matching should work in haskell. I have already spent hours with watching different tutorials but i don't get it.

I have the data type Assignment with the following instance:

    data Assignment = EmptyA | Assign String Integer Assignment
      deriving Show

    myAssn = Assign "x" 1 (Assign "x" 2 (Assign "y" 3 EmptyA))

Now i want to write a function that returns me the number to a given String. For example should lookupA myAssn "y" return 3:

    lookupA :: Assignment -> String -> Integer
    lookupA EmptyA _ = 0 
    lookupA assn s = ???

CodePudding user response:

As you probably know Assignment is a recursive data structure since it can hold instances of itself. To solve this problem, you need to take advantage of this feature of Assignment.

data Assignment = EmptyA | Assign String Integer Assignment
   deriving Show

lookupA :: Assignment -> String -> Integer
lookupA EmptyA _ = 0 
lookupA (Assign name number nAssign) lookingFor
  | name == lookingFor = number
  | otherwise          = lookupA nAssign lookingFor


myAssn = Assign "x" 1 (Assign "y" 2 (Assign "z" 3 EmptyA))

What this code does is as follows:

lookupA (Assign name number nAssign) lookingFor

It destructures the first argument and matches only on Assign data constructors. The using guards, it checks whether the name of this Assignment is equal to what we are looking for. If so, it returns the number, otherwise, it calls itself recursively on the assignment that is inside this assignment. Base case is of course the EmptyA data structure.

  • Related