haskell - Pattern matching for return values -


i know can use pattern matching function parameters this:

fn :: (integral a) => (a,a) -> (a, a) fn (x,y) = (y,x) 

but how can match return value? expect this:

g :: (integral a) => -> g z =   (x, y) = fn (z, z + 5)   x `mod` y 

this results in syntax error. there way match return values? basically, want split returned tuple 2 variables.

the do used syntactical sugar monads. function not monad.

what can use let-clause, like:

g :: (integral a) => -> g z = let (x,y) = fn (z,(z+5)) in x `mod` y

or where-clause:

g :: (integral a) => -> g z = x `mod` y     where (x,y) = fn (z,(z+5))

you can define pattern in lambda-expression, like:

g :: (integral a) => -> g z = (\(x,y) -> x `mod` y) $ fn (z,(z+5))

along these lines, can define helper function pattern matching, like:

g :: (integral a) => -> g z = h $ fn (z,(z+5))     h (x,y) = x `mod` y

this can useful if there several patterns need handled differently (like nothing , just x maybe a type).

say instance defined function:

foo :: int -> int -> maybe int foo x y | x > y = x         | otherwise = nothing 

than can define bar helper function qux handle output of foo, like:

bar :: int -> int -> int bar x y = qux $ foo x y     qux nothing = y           qux (just z) = z 

finally in case of 2-tuples, can decide not use pattern matching, use fst :: (a,b) -> a , snd :: (a,b) -> b, instance:

g :: (integral a) => -> g z = let t = fn (z,(z+5)) in ( fst  t) `mod` (snd t)

but less elegant since here 1 has start thinking fst , snd do, , furtermore if not optimized, can result in additional computation overhead.

which 1 pick depends of course on context , bit on personal taste. since here pattern one, pick let or where pattern, french say: "les goƻts et les couleurs ne se discutent pas.".


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -