Skip to content

Instantly share code, notes, and snippets.

@dvdsgl
Created March 26, 2012 18:30
Show Gist options
  • Save dvdsgl/2208518 to your computer and use it in GitHub Desktop.
Save dvdsgl/2208518 to your computer and use it in GitHub Desktop.
Made easier to 'parse' for Non-haskellers
-- findRoots is a function that takes 3 Doubles and maybe returns a tuple of doubles.
-- Here's its signature, which can be omitted because Haskell infers it:
findRoots :: Double -> Double -> Double -> Maybe (Double, Double)
-- In a C-like language with parameterized types, the type signature might look like:
--
-- static Maybe<Tuple<double,double>> findRoots(double a, double b, double c);
--
-- Maybe is Haskell's 'nullable type'; values of type Maybe t can be thought of as lists
-- containing exactly zero or one value of type t. So, a Maybe Double is either zero or
-- one Double values. You construct an empty Maybe Double with Nothing; you construct a
-- Maybe Double that contains a Double with Just (e.g. "Just 1.0").
-- In the first case, if the first param is zero, we return Nothing (an empty Maybe Double):
findRoots 0 b c = Nothing
-- Here's a translation to psuedo-code you might find more familiar:
--
-- static Maybe<Tuple<double,double>> findRoots(double a, double b, double c) {
-- if (a == 0)
-- return new Nothing<Tuple<double,double>>();
-- }
-- If the first parameter is non-zero, we fall-through to this definition, kind of like
-- cases in a switch statement. This should be easy enough to read with an imperative/OO
-- eye; we assign some 'variables' and return Just a tuple of Doubles:
findRoots a b c = Just (root1, root2)
where uptop = sqrt (b^2 - 4*a*c)
root1 = (-b + uptop) / 2*a
root2 = (-b - uptop) / 2*a
-- Imperative/OO psuedo-code:
--
-- static Maybe<Tuple<double,double>> findRoots(double a, double b, double c) {
-- double uptop = sqrt(b^2 - 4*a*c);
-- double root1 = (-b + uptop) / 2*a;
-- double root2 = (-b - uptop) / 2*a;
-- return new Just<Tuple<double,double>>(new Tuple<double,double>(root1, root2));
-- }
-- Then the main function just calls findRoots and prints the result:
main = print (findRoots 1 6 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment