tuples - Guards in Haskell, performing operations using checks -
so have searched different ways of approaching "if" statements in haskell , have doubt guards, have tuple , want perform +,-,*,/ checking conditions:
given (x,y) if x < y +,* want integers, furthermore check division x mod
y == 0 or not, compiles can-t run
operaciones (x,y) = (x,y) x,y | x < y = [(x, y, '+', x+y), (x, y, '*', x*y)] | (x > y) && (x `mod ` y == 0) = [(x, y, '+', x+y), (x, y, '*', x*y), (x, y, '-', x-y) , (x, y, '/', x/y)] | (x > y) && (x `mod ` y /= 0) = [(x, y, '+', x+y), (x, y, '*', x*y), (x, y, '-', x-y)] | otherwise = [(x, y, '+', x+y), (x, y, '*', x*y), (x, y, '-', x-y) , (x, y, '/', x/y)]
i took idea
but failed, otherwise if x == y
i wouldn't recommend style; you're repeating way much. understand it, want function:
operaciones (x, y) = [ (x, y, '+', x + y), (x, y, '*', x * y), (x, y, '-', x - y), (x, y, '/', x / y) ]
but result list filtered include positive integer results. (incidentally, @ least in english, convention 'integer' includes negative numbers , 0, condition on including difference stricter 'integer results').
i filtering 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 , y have type int or integer, should use div not /
one other note: it's not usual in haskell combine multiple arguments tuple (x, y); if x
, y
separate arguments, function head should written like
operaciones x y =
instead. (the way compiler written, optimizer has work combine tuple (x, y)
separate form anyway, better save work.)
update: can't think of clean way error reporting. end hybrid style, using guards error checking , concatenation success case:
operaciones x y | x <= 0 || y <= 0 = left "use positive numbers" | otherwise = right $ [ (x, y, '+', x + y) ] ++ -- etc. above
you use error
instead of left
, omit right
if wanted to.
Comments
Post a Comment