-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHaskell Chapter 2
More file actions
111 lines (83 loc) · 2.37 KB
/
Copy pathHaskell Chapter 2
File metadata and controls
111 lines (83 loc) · 2.37 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
-- HC2T1 - Task 1: Checking Types in GHCi
-- Expected Types:
-- 42 :: Int
-- 3.14 :: Double
-- "Haskell" :: String
-- 'Z' :: Char
-- True && False :: Bool
-- HC2T2 - Task 2: Function Type Signatures and Implementations
add :: Int -> Int -> Int
add x y = x + y
isEven :: Int -> Bool
isEven n = n `mod` 2 == 0
concatStrings :: String -> String -> String
concatStrings s1 s2 = s1 ++ s2
-- HC2T3 - Task 3: Immutable Variables
myAge :: Int
myAge = 21
piValue :: Double
piValue = 3.14159
greeting :: String
greeting = "Hello, Haskell!"
isHaskellFun :: Bool
isHaskellFun = True
-- Trying to modify any of these will result in a compilation error, e.g.
-- myAge = 30 -- Uncommenting this line would cause an error
-- HC2T4 - Task 4: Converting Between Infix and Prefix Notations
-- Prefix notation
prefixAdd = (+) 5 3
prefixMul = (*) 10 4
prefixBool = (&&) True False
-- Infix notation
infixAdd = 7 + 2
infixMul = 6 * 5
infixBool = True && False
-- HC2T5 - Task 5: Defining and Using Functions
circleArea :: Float -> Float
circleArea r = pi * r * r
maxOfThree :: Int -> Int -> Int -> Int
maxOfThree a b c = max a (max b c)
-- HC2T6 - Task 6: Understanding Int vs Integer
smallNumber :: Int
smallNumber = 262
bigNumber :: Integer
bigNumber = 2127
-- Try evaluating 2^64 :: Int in GHCi manually:
-- > 2^64 :: Int
-- This may cause an overflow depending on your system.
-- HC2T7 - Task 7: Boolean Expressions
boolAndTrue = True && True -- True
boolOrFalse = False || False -- False
boolNotTrue = not False -- True
boolComparison = 5 > 10 -- False
-- Main function to run some tests
main :: IO ()
main = do
putStrLn "-- HC2T2 Function Tests --"
print (add 4 5)
print (isEven 6)
print (concatStrings "Hello, " "World!")
putStrLn "\n-- HC2T3 Immutable Variables --"
print myAge
print piValue
putStrLn greeting
print isHaskellFun
putStrLn "\n-- HC2T4 Infix and Prefix --"
print prefixAdd
print prefixMul
print prefixBool
print infixAdd
print infixMul
print infixBool
putStrLn "\n-- HC2T5 Function Tests --"
print (circleArea 3.0)
print (maxOfThree 10 20 15)
putStrLn "\n-- HC2T6 Int vs Integer --"
print smallNumber
print bigNumber
putStrLn "Try evaluating 2^64 :: Int manually in GHCi to observe overflow behavior."
putStrLn "\n-- HC2T7 Boolean Expressions --"
print boolAndTrue
print boolOrFalse
print boolNotTrue
print boolComparison