-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path10_pattern.hs
executable file
·38 lines (28 loc) · 1014 Bytes
/
10_pattern.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env runhaskell
-- That design pattern is using Higher-Order Functions. These are functions
-- that receive other functions as arguments. The idea is to define the general
-- common behavior in this function, and receiving the specific behavior as
-- arguments.
-- recursiveOp is one example. It receives a function that receives two integers
-- and returns another. It then receives the two parameters of times and power,
-- and returns the final integer.
-- FYI:
-- (+) :: Int -> Int -> Int
-- (*) :: Int -> Int -> Int
recursiveOp :: (Int -> Int -> Int) -> Int -> Int -> Int
recursiveOp op a 1 = a
recursiveOp op a b = op a (self a (b-1))
where self = recursiveOp op
-- What is the type of times? The same! We are using Currying.
-- Fun fact: What is the first name of Mr. Curry?
times = recursiveOp (+)
double = times 2
triple = times 3
-- Another one
power = recursiveOp (*)
square x = power x 2
cube x = power x 3
main :: IO ()
main = do
putStr "double: "
putStrLn (show (cube 2))