Skip to content

Instantly share code, notes, and snippets.

@wcravens
Created September 29, 2016 12:02
Show Gist options
  • Save wcravens/23f8ec6dc8b1bcf6447521314d7300e2 to your computer and use it in GitHub Desktop.
Save wcravens/23f8ec6dc8b1bcf6447521314d7300e2 to your computer and use it in GitHub Desktop.
Leibniz pi calculation; Learn You a Haskell Exercices
stepReverseSign :: (Fractional a, Ord a) => a -> a -> a
stepReverseSign num step = (if num > 0 then -1 else 1) * (abs(num) + step)
piCalc :: (Fractional a, Integral b, Ord a) => a -> (a, b)
piCalc tolerance = piCalc' 1 0.0 tolerance 0
piCalc' :: (Ord a, Fractional a, Integral b) => a -> a -> a -> b -> (a, b)
piCalc' denominator pi tolerance iterations =
| abs( pi' - pi) < tolerance = ( pi', iterations )
| otherwise = piCalc' (stepReverseSign denominator) pi' tolerance (iterations + 1)
where pi' = pi + (4/denominator)
{-
Prelude> :l exercises.hs
[1 of 1] Compiling Main ( exercises.hs, interpreted )
exercises.hs:70:55: error:
• Couldn't match expected type ‘a -> a’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for:
piCalc' :: forall a b.
(Ord a, Fractional a, Integral b) =>
a -> a -> a -> b -> (a, b)
at exercises.hs:67:12
• In the second argument of ‘piCalc'’, namely ‘pi'’
In the expression:
piCalc'
(stepReverseSign denominator) pi' tolerance (iterations + 1)
In an equation for ‘piCalc'’:
piCalc' denominator pi tolerance iterations
| abs (pi' - pi) < tolerance = (pi', iterations)
| otherwise
= piCalc'
(stepReverseSign denominator) pi' tolerance (iterations + 1)
where
pi' = pi + (4 / denominator)
• Relevant bindings include
pi' :: a (bound at exercises.hs:71:9)
tolerance :: a (bound at exercises.hs:68:24)
pi :: a (bound at exercises.hs:68:21)
denominator :: a (bound at exercises.hs:68:9)
piCalc' :: a -> a -> a -> b -> (a, b) (bound at exercises.hs:68:1)
Failed, modules loaded: none.
-}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment