forked from elsys/fp-haskell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Colorize.hs
126 lines (81 loc) · 2.28 KB
/
Colorize.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
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
{-# OPTIONS_GHC -Wall #-}
module Colorize where
backgroundStyle, textStyle :: Int
textStyle = 30
backgroundStyle = 40
black, red, green, yellow, blue, magenta, cyan, white :: Int
black = 0
red = 1
green = 2
yellow = 3
blue = 4
magenta = 5
cyan = 6
white = 7
clear :: Int
clear = 0
-- Exercise 1
getLastDigit :: Int -> Int
getLastDigit x = mod x 10
dropLastDigit :: Int -> Int
dropLastDigit x = quot x 10
-- Exercise 2
getReverseDigits :: Int -> [Int]
getReverseDigits x | x < 10 = [x]
| otherwise = getLastDigit x : getReverseDigits (dropLastDigit x)
-- Exercise 3
toChar :: Int -> Char
toChar 0 = '0'
toChar 1 = '1'
toChar 2 = '2'
toChar 3 = '3'
toChar 4 = '4'
toChar 5 = '5'
toChar 6 = '6'
toChar 7 = '7'
toChar 8 = '8'
toChar 9 = '9'
toChar _ = error "Not a digit"
-- Exercise 4
itoaLoop :: String -> [Int] -> String
itoaLoop acc [] = acc
itoaLoop acc (x:xs) = itoaLoop (toChar x : acc) xs
itoa :: Int -> String
itoa num = itoaLoop [] (getReverseDigits num)
-- Exercise 5
mkStyle :: Int -> String
mkStyle style = "\x1B[" ++ itoa style ++ "m"
mkTextStyle :: Int -> String
mkTextStyle color = mkStyle (color + textStyle)
getStyle :: String -> String
getStyle "blk" = mkTextStyle black
getStyle "red" = mkTextStyle red
getStyle "grn" = mkTextStyle green
getStyle "ylw" = mkTextStyle yellow
getStyle "blu" = mkTextStyle blue
getStyle "mgt" = mkTextStyle magenta
getStyle "cyn" = mkTextStyle cyan
getStyle "wht" = mkTextStyle white
getStyle "clr" = mkStyle clear
getStyle xs = "<" ++ xs ++ ">"
-- Exercise 6
removeStyle :: String -> String
removeStyle text = drop 1 (dropWhile (/= 'm') text)
bleach :: String -> String
bleach ('\x1B':rest) = bleach (removeStyle rest)
bleach (x:rest) = x : bleach rest
bleach [] = []
colorize :: String -> String
colorize ('<':x:y:z:'>':rest) = getStyle [x, y, z] ++ colorize rest
colorize (x:xs) = x : colorize xs
colorize [] = []
-- Extra
mkBackgroundStyle :: Int -> String
mkBackgroundStyle = undefined
getMarkup :: String -> String
getMarkup = undefined
dropMarkup :: String -> String
dropMarkup = undefined
-- What bug does `colorize2` have? It's good that we know it, but we won't fix it now
colorize2 :: String -> String
colorize2 = undefined