-
Notifications
You must be signed in to change notification settings - Fork 0
3. HC3 ‐ Haskell Chapter 3 Practical Tasks: Conditions‐and‐helper‐constructions
Bernard Sibanda edited this page Feb 2, 2025
·
2 revisions
- Define a function
checkNumber :: Int -> String
. - Use an
if-then-else
statement to check if the number is positive, negative, or zero. - Return "Positive", "Negative", or "Zero" accordingly.
- Test your function with
checkNumber 5
,checkNumber (-3)
, andcheckNumber 0
.
- Define a function
grade :: Int -> String
. - Use guards (
|
) to classify scores into grades:- 90 and above: "A"
- 80 to 89: "B"
- 70 to 79: "C"
- 60 to 69: "D"
- Below 60: "F"
- Test your function with
grade 95
,grade 72
, andgrade 50
.
- Define a function
rgbToHex :: (Int, Int, Int) -> String
. - Use
let
bindings to format each color component as a two-character hex string. - Concatenate the three hex values into a single string.
- Test your function with
rgbToHex (255, 0, 127)
andrgbToHex (0, 255, 64)
.
- Define a function
triangleArea :: Float -> Float -> Float -> Float
. - Use
let
to calculate the semi-perimeters
. - Apply Heron’s formula:
sqrt(s * (s - a) * (s - b) * (s - c))
. - Test with
triangleArea 3 4 5
andtriangleArea 7 8 9
.
- Define a function
triangleType :: Float -> Float -> Float -> String
. - Use guards to classify the triangle:
- All sides equal: "Equilateral"
- Two sides equal: "Isosceles"
- No sides equal: "Scalene"
- Test with
triangleType 3 3 3
,triangleType 5 5 8
, andtriangleType 6 7 8
.
- Define
isLeapYear :: Int -> Bool
. - Use
if-then-else
to check:- Divisible by 400: True
- Divisible by 100 but not 400: False
- Divisible by 4: True
- Otherwise: False
- Test with
isLeapYear 2000
,isLeapYear 1900
, andisLeapYear 2024
.
- Define
season :: Int -> String
. - Use guards to return:
- 12, 1, 2 -> "Winter"
- 3, 4, 5 -> "Spring"
- 6, 7, 8 -> "Summer"
- 9, 10, 11 -> "Autumn"
- Test with
season 3
,season 7
, andseason 11
.
- Define
bmiCategory :: Float -> Float -> String
. - Use
where
to calculate BMI:bmi = weight / height^2
. - Use guards to classify BMI:
- <18.5: "Underweight"
- 18.5 to 24.9: "Normal"
- 25 to 29.9: "Overweight"
-
=30: "Obese"
- Test with
bmiCategory 70 1.75
andbmiCategory 90 1.8
.
- Define
maxOfThree :: Int -> Int -> Int -> Int
. - Use
let
to store intermediate max values. - Return the maximum of the three numbers.
- Test with
maxOfThree 10 20 15
andmaxOfThree 5 25 10
.
- Define
isPalindrome :: String -> Bool
. - Use guards:
- If the string has 0 or 1 characters: True
- If the first and last characters match, recursively check the rest.
- Otherwise, return False.
- Test with
isPalindrome "racecar"
,isPalindrome "haskell"
, andisPalindrome "madam"
.