I wouldn't recommend this style; you're repeating yourself way too much. As I understand it, you want this function:
operaciones (x, y) = [
(x, y, '+', x + y),
(x, y, '*', x * y),
(x, y, '-', x - y),
(x, y, '/', x / y) ]
but with the result list filtered to only include positive integer results. (Incidentally, at least in English, the convention is that 'integer' includes negative numbers and 0, so your condition on including the difference is stricter than just 'integer results').
I would do the filtering by concatenating list comprehensions:
operaciones (x, y) =
[ (x, y, '+', x + y) ] ++
[ (x, y, '*', x + y) ] ++
[ (x, y, '-', x + y) | x > y ] ++
[ (x, y, '/', x `div` y) | x >= y, x `mod` y == 0 ] -- I'm assuming x and y have type Int or Integer, so you should use div not /
One other note: it's not usual in Haskell to combine multiple arguments into a tuple like (x, y); so if x
and y
are separate arguments, your function head should be written like
operaciones x y =
instead. (The way the compiler is written, the optimizer actually has to do extra work to combine the tuple for (x, y)
into the separate form anyway, so better to save it the work.)
Update: I can't think of as clean a way to do error reporting. I would probably end up with a hybrid style, using guards for error checking and concatenation for the success case:
operaciones x y
| x <= 0 || y <= 0 = Left "Use positive numbers"
| otherwise = Right $
[ (x, y, '+', x + y) ] ++ -- etc. as above
You could use error
instead of Left
and omit the Right
if you really wanted to.