0

Getting back to my animals example:

type Pig = String
type Lion = String
type Feed = [(Char,Char)]
type Visitors = [(Char,Char)]
type Costs = (Int,Int,Int)

data AnimalHome = Farm Pig Pig Pig Feed | Zoo Lion Lion Lion Feed Visitors

orders :: Char -> AnimalHome -> Costs -> Char
orders stuff Farm p1 p2 p3 feed (cost1,cost2,cost3) = some code here

How would I execute different equations? Say if p1 p2 p3 were entered as "Bert" "Donald" "Horace" I would want it to execute one specific equation, but if they were entered as "Bert" "Donald" "Sheila" I would want it to execute a different equation?

James
  • 161
  • 1
  • 8

1 Answers1

1

The principle is pattern matching. In other words, you can do the following:

orders stuff (Farm p1 p2 p3 feed) (cost1,cost2,cost3) =

  case (p1, p2, p3) of
    ("Bert", "Donald",  "Horace") -> {- something -}
    ("Bert", "Donald",  "Sheila") -> {- something different -}
    (_,      "Abraham", _)        -> {- when p2 is "Abraham" and the others can be anything -}
    _                             -> {- this is the default case -}

to dispatch differently on the names. As you see, an underscore matches on anything and is useful to indicate that you have handled all your special cases and now need something general.

If you want to, you can employ the shorthand available due to the fact that function parameters also are patterns – e.g. you can do this:

orders stuff (Farm "Bert" "Donald"  "Horace" feed) (cost1,cost2,cost3) = {- something -}
orders stuff (Farm "Bert" "Donald"  "Sheila" feed) (cost1,cost2,cost3) = {- something different -}
orders stuff (Farm p1     "Abraham" p3       feed) (cost1,cost2,cost3) = {- when p2 is "Abraham" and the others can be anything -}
orders stuff (Farm p1     p2        p3       feed) (cost1,cost2,cost3) = {- this is the default case -}

In this case, however, I recommend the case…of, both because it is easier to read and because when you want to change something in the arguments you don't have to modify every equation.

kqr
  • 14,791
  • 3
  • 41
  • 72