Summary Files Commits Branches @commit @diff @stats
path: root / Year 2 / Functional Programming / 08-Practice-01.12.2022.hs
blob: 9d50c83acd6cebc5ab145b14af5e7bb3ab91ed17 (plain) (blame)
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
import Data.Char

-- Ex1

incrementAllBy :: [Int] -> Int -> [Int]
incrementAllBy l i
    | length l == 0 = []
    | otherwise = (head l + i):(incrementAllBy (tail l) i)

-- Ex2

multiplyAllBy :: [Int] -> Int -> [Int]
multiplyAllBy l i = map (*i) l    -- section of infix operator https://wiki.haskell.org/Section_of_an_infix_operator

-- Ex3

filterSmallerThan :: [Int] -> Int -> [Int]
filterSmallerThan l i
    | length l == 0 = []
    | head l < i = filterSmallerThan (tail l) i
    | otherwise = (head l):(filterSmallerThan (tail l) i)

-- Ex4

isOrdered :: (Integer -> Integer -> Bool) -> [Integer] -> Bool
isOrdered p l
    | length l <= 1 = True
    | otherwise = (p (head l) (head (tail l))) && (isOrdered p (tail l))

toList :: Integer -> [Integer]
toList i
    | i == 0 = []
    | otherwise = (toList (div i 10)) ++ [mod i 10]

isAscending :: Integer -> Bool
isAscending i = isOrdered (\a b -> a < b) (toList i)

-- Ex5

digits :: String -> String
digits s
    | s == "" = ""
    | '0' <= head s && head s <= '9' = (head s):(digits (tail s))
    | otherwise = (digits (tail s))

-- Ex6

digitsSum :: String -> Int
digitsSum s
    | s == "" = 0
    | isDigit (head s) = (ord (head s)) - 48 + digitsSum (tail s)
    | otherwise = digitsSum (tail s)

-- Ex7

capitalize :: String -> String
capitalize s = map toUpper s

-- Ex8

isCapitalized :: String -> Bool
isCapitalized "" = True
isCapitalized s  = isUpper (head s) && isCapitalized (tail s)

main :: IO()
main = do
    print (incrementAllBy [1, 2, 3, 4] 2)
    print (multiplyAllBy [1, 2, 3, 4] 3)
    print (filterSmallerThan [8, 48, 38, 2, 62, 10, 94, 20] 20)
    print (isAscending 123456)
    print (digits "adlj1djfahf adfhapufh dufh 2 afjgbsd 3 hg")
    print (digitsSum "asdkljfkj g1jgfh gufh 3 fgkjfg 4 akldjga 6")
    print (capitalize "abcdefg")
    print (isCapitalized "ABCDe")