summaryrefslogtreecommitdiff
path: root/src/Miscellaneous.hs
blob: 8081c93c4ed0949b603186e0441958f5df4a5e2c (plain)
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
module Miscellaneous(
    if',
    (?),
    (.:),
    selectFrom,
    readMaybe,
    partBeforeAfter
    ) where




--  This source is licensed under Creative Commons CC0 v1.0.

--  To read the full text, see license.txt in the main directory of this repository
--  or go to https://creativecommons.org/publicdomain/zero/1.0/legalcode.txt

--  For a human readable summary, go to https://creativecommons.org/publicdomain/zero/1.0/




import qualified Control.Monad as Con
import qualified Data.List as List
import qualified Data.Maybe as Maybe




if' :: Bool -> t -> t -> t
if' a b c = if a then b else c




infixr 1 ?
(?) :: Bool -> t -> t -> t
(?) = if'




--  with this, I have truly gone dotty
infixr 9 .:
(.:) :: (a -> b) -> (c -> d -> a) -> c -> d -> b
(.:) = (.).(.)




--  kinda functions like poor man's sql
--  first argument is the indices of the items you want in the results
--  second argument is index-item pairs to dictate what records are acceptable to select from
--  third argument is the list of items that makes up the record under consideration
--  then if the record was deemed acceptable you get the bits you wanted
--  (note that all indices start from 1)
selectFrom :: (Num t, Eq t, Eq a, Enum t) => [t] -> [(t,a)] -> [a] -> Maybe [a]
selectFrom pick has from =
    let foldFunc r i =
            let check = List.lookup (fst i) has
            in if (Maybe.isNothing check || Maybe.fromJust check == snd i)
                then if (List.elem (fst i) pick)
                        then Just (r ++ [snd i])
                        else Just r
                else Nothing
    in Con.foldM foldFunc [] (zip [1,2..] from)




readMaybe :: Read a => String -> Maybe a
readMaybe s =
    case reads s of
        [(val, "")] -> Just val
        _ -> Nothing




partBeforeAfter :: (Eq a) => a -> [a] -> ([a],[a])
partBeforeAfter item list =
    let (x,y) = List.break (== item) list
    in if (length y <= 1)
        then (x,[])
        else (x,tail y)