Skip to content

Instantly share code, notes, and snippets.

@MgaMPKAy
Created February 22, 2012 14:54
Show Gist options
  • Save MgaMPKAy/1885427 to your computer and use it in GitHub Desktop.
Save MgaMPKAy/1885427 to your computer and use it in GitHub Desktop.
some simple recursive function
module Recursive where
g :: Int -> Int -> Int
g 0 _ = 0
g m n = g (m - 1) (2 * n) + n
f :: Int -> Int
f 0 = 1
f n = n * f (div n 2)
-- tail recursive
f' :: Int -> Int
f' n = fi n 1
where
fi i acc =
case i of
0 -> acc
i1 -> fi (div i1 2) (i1 * acc)
testF :: Bool
testF = and $ map test [0..1000]
where test n = f' n == f' n
-- tail recursive
mySqrt :: (Fractional a, Ord a) => a -> a -> a -> a
mySqrt x guess e =
if goodEnough
then guess
else mySqrt x nextGuess e
where
goodEnough = abs (guess ^ (2::Int) - x) < e
nextGuess = (1/2*(guess + x / guess))
akm 0 n = n + 1
akm m 0 = akm (m - 1) 1
akm m n = akm (m - 1) (akm m (n - 1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment