-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathcolor.ml
67 lines (52 loc) · 2.07 KB
/
color.ml
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
(*
CS51 Lab 7
Modules & Functors
A module for colors and color names
The representation for colors in this implementation is really obscure
and arguably unnecessarily so. By the way, it also has some bugs so it
doesn't pass all the unit tests. No need to debug it though. You'll be
replacing it wholesale with a simpler implementation. *)
(*
SOLUTION
In this implementation, we simply use int triples for the rgb
channels. By keeping the data in a more structured form, all of the
conversions are simplified.
You might have used a record type instead of a tuple, for instance,
type color = { red : int; green : int; blue : int } ;;
That could work too. And the user of the module (lab7_part2.ml)
wouldn't be able to tell the difference, just like it can't tell the
difference with the obfuscated implementation in the original
color.ml. *)
(* 8-bit RGB channel colors *)
type color = int * int * int ;;
(* Some standard color names *)
type color_name =
| Red | Green | Blue
| Orange | Yellow | Indigo | Violet ;;
(* to_color r g b -- Returns the color corrersponding to the RGB
values given by r, g, and b *)
let to_color (r : int) (g : int) (b : int) : color =
r, g, b ;;
(* red c -- Returns the red channel value for the color c *)
let red (c : color) : int =
match c with
| (r, _g, _b) -> r ;;
(* green c -- Returns the green channel value for the color c *)
let green (c : color) : int =
match c with
| (_r, g, _b) -> g ;;
(* blue c -- Returns the blue channel value for the color c *)
let blue (c : color) : int =
match c with
| (_r, _g, b) -> b ;;
(* color_named name -- Returns the color (as RGB representation)
corresponding to the color name *)
let color_named (name : color_name) : color =
match name with
| Red -> to_color 255 0 0
| Green -> to_color 0 255 0
| Blue -> to_color 0 0 255
| Orange -> to_color 255 165 0
| Yellow -> to_color 255 255 0
| Indigo -> to_color 75 0 130
| Violet -> to_color 240 130 240