Haskell way to joint two small functions. Syntax advice needed

100 Views Asked by At

I'm new to Haskell and I'm having kind of a hard time joining two sections of code for this program. What it does (or should do) is to let me know if a triangle is isosceles by the theorem of cosenes. Here it is what I thought would work:

--Determine if a triangle is isosceles by the cosene theroem

module Main where
sides :: (Float, Float, Float) -> (Float, Float, Float)
sides (a, b, c) = (x, y, z)
 where
   x = acos((b^2 + c^2 - a^2) / (2 * b * c))
   y = acos((a^2 + c^2 - b^2) / (2 * a * c))
   z = acos((a^2 + b^2 - c^2) / (2 * a * b))  

theorem :: (Float, Float, Float) -> String
theorem (x, y, z)
  |(x==y && x/=z) = "Es isosceles"
  |(x==z && x/=y) = "Es isosceles"
  |(y==z && y/=x) = "No es isosceles"
 
main :: IO()
main = do
   print "Please type the size of the triangle faces: "
   (a, b, c) <- getLine
   (x, y, z) <- sides (a, b, c)
   string <- theorem(x, y, z)
   print string
1

There are 1 best solutions below

0
On

I'm not sure that after my advice updated code will run, but I see some problems in this code:

  1. print isn't exactly what you want, because strings will be printing with quotes ("Please type the size of the triangle faces: " instead Please type the size of the triangle faces: ). If you want print a string, replace print to putStrLn

  2. getLine has type IO String, so pattern matching with (a, b, c) will be failed. But you can write read <$> getLine - it will apply function read which convert a string to a value of any readable type (in this case it is (Float, Float, Float)) to the input string. But the input string must be in format (_, _, _) (for example (1, 1, 1))

  3. when you write a <- b in do-block, it means that b has type m t where m is Monad, and a has type t. sides has type (Float, Float, Float) -> (Float, Float, Float), so you can't write this instead b in the expression above. But you can write let a = b where both a and b has the same type t. So you can write let (x, y, z) = sides (a, b, c) instead (x, y, z) <- sides (a, b, c). Similarly with string <- theorem(x, y, z)

  4. theorem don't defined for all values (x, y, z) because you consider cases with the pair of equals value and one not equal