How to use guards with Let in Haskell

Asked

Viewed 117 times

1

I wanted to make that same problem calculating the roots of a second-degree function, but using Let.

raizes2 :: Float -> Float -> Float -> (Float, Float)
raizes2 a b c 
  |delta < 0 = error "Delta nao pode ser menor que zero"
  |a == 0 = error "A nao pode ser zero"
  |otherwise = ((-b + (sqrt(delta)))/2*a, (-b - (sqrt(delta)))/2*a)
where
delta = (b^2 - 4*a*c)

2 answers

2

You have to use expressions case. For example:

raizes2 :: Float -> Float -> Float -> (Float, Float)
raizes2 a b c = let delta = (b^2 - 4*a*c)
                in case compare delta 0 of
                     LT -> error "Delta nao pode ser menor que zero"
                     _  -> if a == 0
                           then error "A nao pode ser zero"
                           else ( (-b + (sqrt(delta)))/2*a
                                , (-b - (sqrt(delta)))/2*a )

It’s a little different because case only compares equalities. And what is compared is static, that is, will always be the result of compare delta 0, which may be LT, GT or EQ. How your patterns involve comparing not only the value of delta, it is necessary to use the case _ (that accepts anything) and within it create a if (or another case) to compare the value of a.

If you want to read a little bit about these structures, the page about case is translated into Wikibook in English.

0

You cannot use guards inside the Let directly. Guards come before the definition of the expression to be evaluated, and Let is already that expression. But one way to solve (improperly) the problem is to define an auxiliary function within Let, and in that definition use guards

raizes2 a b c = let delta = (b^2 - 4*a*c)
                    auxiliar
                        |delta < 0 = error "Delta nao pode ser menor que zero"
                        |a == 0 = error "A nao pode ser zero"
                        |otherwise = ((-b + (sqrt(delta)))/2*a, (-b - (sqrt(delta)))/2*a)
                in auxiliar

Like I said, inelegant....

Browser other questions tagged

You are not signed in. Login or sign up in order to post.