Since I'm not entirely sure what a string of numbers means, I just assumed the function gets a list of integers.
import Data.List (partition)
fight :: [Int] -> String
fight = answer . add . partition even
add (evens, odds) = (sum evens, sum odds)
answer (evens, odds)
| evens == odds = "Even and Odd are the same"
| evens > odds = "Even is greater than Odd"
| otherwise = "Odd is greater than Even"
Could you explain what add (evens, odd) is (data type) and what does this piece do please?
add (evens, odd)
Sure! Let's start at partition, since we pass its output to add. Partition takes a predicate function and returns a tuple ([Int], [Int]) with the items of the list for which the predicate is true in the first position and the items for which the predicate is false in the second position. In this case, in the first position we'll have all the even numbers and in the second all the odd numbers, since we're using even as predicate.
Then add receives this tuple, which I destructure for convenience, and applies the function sum to both elements, which sums all the items in each list.
And the function signature for add would look like this.
add :: ([Int], [Int]) -> (Int, Int)
Lastly, answer takes the output of add and checks the conditions in the guards (the | <condition> thing) and returns the string for the first condition that matches or the string after otherwise if none matches.
Awesome, thanks for your answer! I didn't know the add function could take a tuple. Good to know!
We're a place where coders share, stay up-to-date and grow their careers.
We strive for transparency and don't collect excess data.