here's a program I wrote...can anyone tell me what I'm doing wrong? inb4 use <insert fave language>
roots :: (Float, Float, Float) -> (Float, Float)
roots (a,b,c) = (x1, x2) where
x1 = e + (sqrt d) / (2 * a)
x2 = e - (sqrt d) / (2 * a)
d = (b * b) - (4 * a * c)
e = - b / (2 * a)
main :: IO Float -> IO
main = do{
print "a = "; a <- readLn;
print "b = "; b <- readLn;
print "c = "; c <- readLn;
ans <- roots (a,b,c); print ans;
}
>>1
I'm not installing a Haskell interpreter to check this out, but I have a funny feeling that the order in the where clause matters and that the x1 and x2 should come after d and e. Of course, it would be a lot easier if you would give us the output. Also, High school maths would tell you that the output of the quadratic formula can be two complex numbers, and I doubt Haskell's Float covers that (but I am open to being proved wrong)
Name:
52010-05-05 19:28
Also, here's how you do it in a real language (define (solve-quadratic a b c)
(let ((determinant (- (expt b 2)
(* 4 a c)))
(two-a (* a 2)))
(values (/ (+ (- b) (sqrt determinant)) two-a)
(/ (- (- b) (sqrt determinant)) two-a))))
Name:
Anonymous2010-05-05 19:51
>>1
Easy solution, I hope. x1 = e + (sqrt d) / (2 * a) x2 = e - (sqrt d) / (2 * a) d = (b * b) - (4 * a * c)
e = - b / (2 * a)
x1 = e + (sqrt d) / (2 * a)
x2 = e - (sqrt d) / (2 * a)
You should only have to make sure your math is correct.
>>1,7,8
What the hell is with Haskellers and not using real variable names.
Name:
Anonymous2010-05-05 20:45
main :: IO Float -> IO
"IO" isn't a value you can return. You need to perform some type of I/O. In this case, it should be unit I/O: IO (). This is the first step towards getting a meaningful error message.
Secondly, your main function doesn't take any parameters. The entire type should be "main :: IO ()".
Then you have to figure out how to perform I/O properly. Remember that the type signature of roots is not IO (Float,Float). This means that in a Do block, you shouldn't use "<-" to bind its value. Instead, just use let ans = roots (a,b,c) -- voilà, it works!
>>1
Also, why are you using braces? Indentation looks much nicer.
And you should rather have roots :: Float -> Float -> Float -> (Float, Float), it's customary for functions to be curried.
Something more idiomatic might be like this: main :: IO ()
main = do a <- ask "a = "
b <- ask "b = "
c <- ask "c = "
let ans = roots' a b c
print ans
ask :: (Show a, Read b) => a -> IO b
ask s = do print s
readLn
roots' :: (Floating a) => a -> a -> a -> (a, a)
roots' a b c = (x1, x2) where
x1 = left + right
x2 = left - right
left = -b / (2 * a)
right = sqrt ((b^2) - 4 * a * c) / (2 * a)
...or better yet: roots :: (Floating a) => a -> a -> a -> (a, a)
roots a b c = (-b) `plusOrMinus` sqrt (b^2 - 4*a*c) `allOver` (2*a)
where plusOrMinus x y = (x+y, x-y)
allOver (x, y) z = (x/z, y/z)
Name:
Anonymous2010-05-05 23:44
Why are people torturing themselves with learning this son of a bitch language? It's not even hip.