0

Sorry, this may seem similar to an earlier question but I am still a little confused. Here is the same code I am using as an 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

But this time I want to execute different functions if the costs are different i.e. (1,3,9) executes a different equation to (0,0,16) etc.

kqr
  • 14,791
  • 3
  • 41
  • 72
James
  • 161
  • 1
  • 8

2 Answers2

1

You can adapt the answers to your previos similar questions for this case. Remember that a 3-tuple or triple (i.e. your type Costs) is just another data type. If there were no tuples in Haskell, you could write:

data Triple a b c = Triple a b c

and it would behave exactly as 3-tuples do! The only difference is that Hakell supports a more convenient syntax both for tuple expressions and tuple patterns.

Now for Patterns in general: Simplifying a bit, there are basicall 3 possibilities to write them:

  • a literal (suitable only for data types that support this, like String, Int, etc.), matches only that value.
  • a variable, matches any value
  • a data constructor, applied to patterns. Matches values constructed with that data constructor where the subpatterns match.

Turns out that you already wrote correct patterns in your question:

i.e. (1,3,9) executes a different equation to (0,0,16)

hence

orders stuff (Farm p1 p2 p3 feed) (1,3,9) = some code here
orders stuff (Farm p1 p2 p3 feed) (0,0,16) = some other code here

It probably would help us to help you if we could understand what your specific issues with pattern matching is. i.e. why you couldn't just try to come up with that yourself, as it feels quite natural, does it not?

Ingo
  • 36,037
  • 5
  • 53
  • 100
  • That does yes, but sometimes in programming I come across concepts which seem very counter-intuitive! – James Nov 20 '13 at 16:53
0

If you really mean to use different functions with different integers, it's fine to use pattern matching

orders stuff (Farm p1 p2 p3 feed) (1,3,9) = -- one thing
orders stuff (Farm p1 p2 p3 feed) (0,0,16) = -- another thing

but I'd only really use that with 0, not other values. Really what you're after is called guards:

orders stuff (Farm p1 p2 p3 feed) (a,b,c) 
       | a == 0 && b == 0  = -- one thing
       | a*b^2=c           = -- another thing
       | b < 0             = -- a third thing

and each condition is checked in turn - only the first true condition gets to run its code.