aboutsummaryrefslogtreecommitdiff
path: root/src/Common.hs
blob: 91bf708259f6411f9661dda53141c3f078d8208b (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
module Common
  ( toLower
  , trim
  , trimWith
  , splitOn
  , split2
  , replace
  , (!!?)
  , findVal
  , maybeAt
  , startsWith
  , delete
  )
where

import Data.Char (isSpace)
import qualified Data.Char as C
import Data.List (find, stripPrefix)
import Intro

trim :: String -> String
trim = f . f
 where
  f = reverse . dropWhile isSpace

trimWith :: (Char -> Bool) -> String -> String
trimWith p = f . f
 where
  f = reverse . dropWhile p

splitOn :: (a -> Bool) -> [a] -> [[a]]
splitOn p s = case dropWhile p s of
  [] -> []
  s' -> w : splitOn p s''
   where
    (w, s'') = break p s'

split2 :: (a -> Bool) -> [a] -> ([a], [a])
split2 p s =
  case break p s of
    (x, _ : y) -> (x, y)
    (x, []) -> (x, [])

infix 9 !!?

(!!?) :: [a] -> Int -> Maybe a
(!!?) xs i
  | i < 0 = Nothing
  | otherwise = go i xs
 where
  go :: Int -> [a] -> Maybe a
  go 0 (x : _) = Just x
  go j (_ : ys) = go (j - 1) ys
  go _ [] = Nothing

maybeAt :: Int -> [a] -> Maybe a
maybeAt = flip (!!?)

toLower :: String -> String
toLower = fmap C.toLower

startsWith :: (a -> Bool) -> [a] -> Bool
startsWith _ [] = False
startsWith p (x : _) = p x

findVal :: (a -> Bool) -> [(a, b)] -> Maybe b
findVal p xs = snd <$> find (p . fst) xs

replace :: (Eq a) => [a] -> [a] -> [a] -> [a]
replace [] to xs = go xs
 where
  go [] = to
  go (x : xs') = to ++ x : go xs'
replace from to xs | Just xs' <- stripPrefix from xs = to ++ replace from to xs'
replace from to (x : xs) = x : replace from to xs
replace _ _ [] = []

delete :: (a -> Bool) -> [a] -> (Maybe a, [a])
delete p = foldr f (Nothing, [])
 where
  f x (Nothing, xs) | p x = (Just x, xs)
  f x (m, xs) = (m, x : xs)