Reputation: 735
I am having problems with the following exercise:
Write a function that receives three Ints and sums them if they are all positive and returns 0 (zero) otherwise.
What I have done is the following:
sum' :: int -> int -> int -> int
sum' x y z = if x >= 0, y >= 0, z >= 0 then x+y+z else 0
I don't know how to make multiple conditions on an if, not sure if this is done with logical "connectors" (like ||
or &&
in Java) or if it is done in a similar way to the code I wrote.
Upvotes: 2
Views: 14849
Reputation: 835
Or using guards, which would make it look almost exactly like the human version of the definition:
sum' :: Int -> Int -> Int -> Int
sum' x y z
| x >= 0 && y >= 0 && z >= 0 = x+y+z
| otherwise = 0
On a side note, always remember that types start with a capital letter. In your case, your type signature should use "Int" instead of "int".
I hope this helps.
Upvotes: 4
Reputation:
It can be done in multiple ways.
For example, using &&
:
sum' :: Int -> Int -> Int -> Int
sum' x y z = if x >= 0 && y >= 0 && z >= 0 then x+y+z else 0
Or using all
and a list:
sum' :: Int -> Int -> Int -> Int
sum' x y z = if all (>= 0) xs then sum xs else 0
where xs = [x, y, z]
Upvotes: 9