2403683de36eeb1aed4359bf7cc8fbfbfccb0bcb
[fp1415.git] / fp2 / week2 / mart / StdMaybe.dcl
1 definition module StdMaybe
2
3 // ********************************************************************************
4 // Clean StdLib library module, version 1.0
5 // ********************************************************************************
6
7 from StdFunc import :: St;
8 from StdOverloaded import class ==(..);
9
10 :: Maybe x
11 = Just x
12 | Nothing
13
14 isJust :: !(Maybe .x) -> Bool // case @1 of (Just _) -> True; _ -> False
15 isNothing :: !(Maybe .x) -> Bool // not o isJust
16 fromJust :: !(Maybe .x) -> .x // \(Just x) -> x
17
18 // for possibly unique elements:
19 u_isJust :: !u:(Maybe .x) -> (!Bool, !u:Maybe .x)
20 u_isNothing :: !u:(Maybe .x) -> (!Bool, !u:Maybe .x)
21
22 accMaybe :: .(St .x .a) !u:(Maybe .x) -> (!Maybe .a,!u:Maybe .x)
23 // accMaybe f (Just x) = (Just (fst (f x)),Just (snd (f x)))
24 // accMaybe f Nothing = (Nothing,Nothing)
25
26 mapMaybe :: .(.x -> .y) !(Maybe .x) -> Maybe .y
27 // mapMaybe f (Just x) = Just (f x)
28 // mapMaybe f Nothing = Nothing
29
30 instance == (Maybe x) | == x
31 // Nothing==Nothing
32 // Just a ==Just b <= a==b
33
34 maybeToList :: !(Maybe .a) -> [.a];
35 // returns list with no or one element
36
37 listToMaybe :: ![.a] -> .Maybe .a;
38 // returns Just head of list if possible
39
40 catMaybes :: ![Maybe .a] -> .[.a];
41 // catMaybes ms = [ m \\ Just m <- ms ]