-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFunctionSpec.hs
More file actions
62 lines (49 loc) · 2.11 KB
/
FunctionSpec.hs
File metadata and controls
62 lines (49 loc) · 2.11 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
module FunctionSpec where
import Test.Hspec
buildNum :: Int -> Int -> Int -> Int
buildNum hundreds tens ones = hundreds * 100 + tens * 10 + ones
buildNumFromTuple :: (Int, Int, Int) -> Int
buildNumFromTuple (hundreds, tens, ones) = hundreds * 100 + tens * 10 + ones
buildNumFromList :: [Int] -> Int
buildNumFromList list = buildNumFromReversedList $ reverse list
buildNumFromReversedList :: [Int] -> Int
buildNumFromReversedList [] = 0
buildNumFromReversedList (x: xs) = x + 10 * buildNumFromReversedList xs
spec :: Spec
spec = do
it "functions are automatically curried" $ do
buildNum 1 2 3 `shouldBe` 123
it "getting values from a tuple" $ do
buildNumFromTuple (1, 2, 3) `shouldBe` 123
it "getting values from a list" $ do
buildNumFromList [1, 2, 3] `shouldBe` 123
it "different ways to define functions" $ do
let myNumbers = [1,2]
timesTwo x = x * 2
map timesTwo myNumbers `shouldBe` [2,4]
map (\x -> x * 2) myNumbers `shouldBe` [2,4]
map (* 2) myNumbers `shouldBe` [2,4]
it "compose functions" $ do
let timesTwo x = x * 2
plusTwo x = x + 2
timesTwoThenPlusTwoA = \x -> plusTwo (timesTwo x)
plusTwoThenTimesTwoA = \x -> timesTwo (plusTwo x)
timesTwoThenPlusTwoB = \x -> plusTwo $ timesTwo x
plusTwoThenTimesTwoB = \x -> timesTwo $ plusTwo x
timesTwoThenPlusTwoC = plusTwo . timesTwo
plusTwoThenTimesTwoC = timesTwo . plusTwo
timesTwoThenPlusTwoA 3 `shouldBe` 8
plusTwoThenTimesTwoA 3 `shouldBe` 10
timesTwoThenPlusTwoB 3 `shouldBe` 8
plusTwoThenTimesTwoB 3 `shouldBe` 10
timesTwoThenPlusTwoC 3 `shouldBe` 8
plusTwoThenTimesTwoC 3 `shouldBe` 10
it "surrounding an infix operator with parentheses makes it prefix" $ do
(1 + 2) `shouldBe` 3
((+) 1 2) `shouldBe` 3
it "surrounding an infix operator with parentheses allows passing it as an argument (higher-order)" $ do
zipWith (\x y -> x + y) [1, 2] [3, 4] `shouldBe` [4, 6]
zipWith (+) [1, 2] [3, 4] `shouldBe` [4, 6]
it "surrounding a normal (prefix) identifier with backticks makes it infix" $ do
shouldBe True True
True `shouldBe` True