Home > Blockchain >  Checking if the first 2 numbers inputted are larger than the third and if so printing true or false
Checking if the first 2 numbers inputted are larger than the third and if so printing true or false

Time:11-08

I'm writing a simple program in haskell which takes 3 floats for input. The first 2 are added together and then it checks if they are smaller than the 3rd float, if so it will print False otherwise it will print True

This is my code:

validTriangle :: Float -> Float -> Float -> Bool

validTriangle x y z
    | x y < z = False
    | x z < y = False
    | z y < x = False
    | otherwise = True

Every numbers I enter I get the same error: Variable not in scope: validTriangle :: t0 -> t1 -> t2 -> t

Ive tried inputting multiple numbers to see if it would solve the error.

CodePudding user response:

A simpler variant is checking that the sum of the first two is larger than the third one, so:

validTriangle :: (Num a, Ord a) => a -> a -> a -> Bool
validTriangle x y z = x   y >= z

or shorter:

validTriangle :: (Num a, Ord a) => a -> a -> a -> Bool
validTriangle x y = (x   y >=)

or shorter:

validTriangle :: (Num a, Ord a) => a -> a -> a -> Bool
validTriangle x = (>=) . (x )

CodePudding user response:

I hope this will be helpful:

validTriangle :: Float -> Float -> Float -> Bool

validTriangle x y z
| x y < z = False
| x z < y = False
| z y < x = False
| otherwise = True

main = do
putStrLn "Enter 3 floats"
xStr <- getLine
yStr <- getLine
zStr <- getLine
let x = (read xStr :: Float)
let y = (read yStr :: Float)
let z = (read zStr :: Float)
print (validTriangle x y z)

or

validTriangle x y z = x   y > z && x   z > y && y   z > x

main = do
putStrLn "Enter 3 floats"
xStr <- getLine
yStr <- getLine
zStr <- getLine
let x = (read xStr :: Float)
let y = (read yStr :: Float)
let z = (read zStr :: Float)
print (validTriangle x y z)

The first answer defines the validTriangle function, which takes three floats as input and returns a Boolean value. The function checks if the sum of the first two floats is less than the third float, and if so, returns False. Otherwise, it returns True.

The second answer defines the validTriangle function using a single line of code. This is called a "point-free" definition, and it is equivalent to the first definition.

Both answers will produce the same result when run.

  • Related