Skip to content

Instantly share code, notes, and snippets.

@taka011239
Created March 31, 2013 14:56
Show Gist options
  • Save taka011239/5280883 to your computer and use it in GitHub Desktop.
Save taka011239/5280883 to your computer and use it in GitHub Desktop.
plus :: Int -> Int -> Int
plus m 0 = m
plus m n
| n > 0 = plus m (n - 1) + 1
| n < 0 = plus m (n + 1) - 1
minus :: Int -> Int -> Int
minus m 0 = m
minus m n
| n > 0 = minus m (n - 1) - 1
| n < 0 = minus m (n + 1) + 1
power :: Float -> Float -> Float
power m 0.0 = 1
power m 1.0 = m
power m n
| n > 0.0 = power m (n - 1) * m
| n < 0.0 = power m (n + 1) / m
-- tail call optimization
plus' :: Int -> Int -> Int
plus' m n = plus'' m n m
plus'' :: Int -> Int -> Int -> Int
plus'' m 0 acc = acc
plus'' m n acc
| n > 0 = plus'' m (n - 1) (acc + 1)
| n < 0 = plus'' m (n + 1) (acc - 1)
minus' :: Int -> Int -> Int
minus' m n = minus'' m n m
minus'' :: Int -> Int -> Int -> Int
minus'' m 0 acc = acc
minus'' m n acc
| n > 0 = minus'' m (n - 1) (acc - 1)
| n < 0 = minus'' m (n + 1) (acc + 1)
power' :: Float -> Float -> Float
power' m n
| n > 0.0 = power'' m n m
| n <= 0.0 = power'' m n 1.0
power'' :: Float -> Float -> Float -> Float
power'' m 0.0 acc = acc
power'' m n acc
| n > 0.0 = power'' m (n - 1.0) (acc * m)
| n < 0.0 = power'' m (n + 1.0) (acc / m)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment