Save this file as power.hs (hs. Is Haskell file extension)
Run the file using Winhugs or GHCi
Ayumilove Haskell Tutorial 4
Ayumilove’s Diary:
This tutorial teaches using recursion/loop/iteration for power function
Power :: Int -> Int -> Int
Power b 0 = 1 <<<<<<<<<<< power of zero is 1
Power b p | p > 0 = power(b)(p-1)*b
-- Save this file as power.hs (.hs is haskell file extension)
-- Run the file using the WinHugs or GHCi
{-
Hi guys! Ayumilove here teaching Haskell Programming! I’ll be continuing with part 4 exercise. In today’s lesson, we will be using the same thing we have done in the previous tutorial; however, with a slight change. 27/07/2008
We will be using recursion/loop/iteration to do math formula (power)
Example:
2 to the power of 3 is 8 = 2^3-8
or in simpler form: 2*2*2 = 8
-}
{-
1st: define function name and its data type.
We will need 2 input values, 1st is base, 2nd is power
b = BASE: 2
p = POWER: 3
2^3=8
-}
{-
The power function receives 2 input values, the guard/if-ten will check if the power is greater than zero, it will proceed with the actions
Power b p | p > 0 =
Let us take an example to demonstrate how Haskell work
Example 2 to the power of 3.
Power b p | p > 0 = power(b)(p-1)*b
Power 2 3| 3 > 0 = power(2)(3-1)*2
Power 2 3| 3 > 0 = power(2)(2)*2
Haskell check value, 2 is greater than 0, if yes, repeat
Power 2 3| 2 > 0 = (power(2)(2-1)*2)*2
Power 2 3| 2 > 0 = (power(2)(1)*2)*2
Haskell check value, 1 is greater than 0, if yes, repeat
Power 2 3| 2 > 0 = ((power(2)(1-1)*2)*2)*2
Power 2 3| 2 > 0 = ((power(2)(0)*2)*2)*2
Haskell check value, 0 is not greater than 0, so replace
power(2)(0) with 1, power(b)(0)=1, see the match??
We have defined that when “power b 0 = 1”
Power 2 3| 2 > 0 = ((1*2)*2)*2
Power 2 3| 2 > 0 = 1*2*2*2
Power 2 3| 2 > 0 = 8 << this is the answer, simple!
NOTE: The () brackets are just to group number, not for multiplication like in mathematics
-}
{-
When the base is power with 0, the result is 1
Example 2: to the power of zero is 12^0 = 1
-}
{-
Note: The output data type is determined by input.
-}
Hi guys! Ayumi here.
To load the .hs script, drag the file into this window or you could type what the lengthy file location.
Once loaded, then type out the function name and value
Power 2 3
8
Power 2 4
16
Power 2 5
32
Power 2 6
64
Power 3 6
729
Power 2 0
1
Power 10000 0
1
Power 9999 0
1
Power 9 2
81
9 to the power of 2 is 9 * 9
Power of 9 3
729
Power of 9 * 9 * 9
729
End of Ayumilove Haskell Programming tutorial.
Transcription by: Scribe4you Transcription Services