I saw this exercise in a book and I am trying to do it but I have a question.
What I am trying to do is define a data type Shape suitable for representing triangles, squares and circles, and then define a function area :: Shape -> Float which returns the area of a given Shape.
My code right now:
data Shape = Triangle Float Float Float
| Square Float | Circle Float
area :: Shape -> Float
area (Triangle a b c) = sqrt (s*(s-a)*(s-b)*(s-c))
where
s = (a+b+c)/2
area Square d = d*d
area Circle r = pi * r^2
The error I get:
Haskell.hs:4:1:
Equations for `area' have different numbers of arguments
Haskell.hs:(4,1)-(6,37)
Haskell.hs:7:1-19
Failed, modules loaded: none.
I saw the solution is this :
data Shape = Triangle Float Float Float
| Square Float | Circle Float
area :: Shape -> Float
area ( Triangle a b c )
= triarea a b c
area ( Square d )
= d * d
area ( Circle r )
= pi * r^2
triarea a b c
= sqrt( s * (s-a) * (s-b) * (s-c) )
where
s = (a+b+c)/2
How is this different from my implementation?? What does my error mean?
Thanks :)
You need to surround
Square d
andCircle r
in parentheses. Otherwise they'll be parsed as two arguments, not one.See, for example, this answer: "Function application binds tighter than any infix operator. Burn this into your brain in letters of fire." (That's not completely pertinent here; rather, function application is left-associative, even on the lhs of a definition.)