forked from haskell-game/tiny-games-hs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
minify.hs
executable file
·66 lines (58 loc) · 1.57 KB
/
minify.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
#!/usr/bin/env -S runghc -XUnicodeSyntax -XBlockArguments
import Data.Char
import Data.List
import System.Environment
import System.Exit
import System.FilePath
overlay function list =
let pairs = fmap function (zip list (tail list))
in (fst . head) pairs : fmap snd pairs
specialTokens =
[ "("
, ","
, ")"
, "{"
, ";"
, "}"
, "["
, "]"
, "←"
, "→"
, "<-"
, "->"
, "∷"
, "::"
, "@"
, "\\"
]
isAllowedInName = or . flip fmap [isAlphaNum, (== '_'), (== '\'')] . flip ($)
addWhiteRoom = overlay \(this, next) →
if this `elem` specialTokens
then (this, next)
else
if (isAllowedInName . last) this && (isAllowedInName . head) next
then (this, " " <> next)
else (this, next)
cut fit list = (last . filter (fit . fst)) (zipWith splitAt [0 ..] (replicate (length list + 1) list))
main = do
target ← fmap (!! 0) getArgs
if takeExtension target /= ".hs"
then exitFailure
else tailor target
tailor target = do
cloth ← readFile target
let
(snowflakes, leftovers) = cut (all \line → (head line == '#')) (lines cloth)
tokens = words (unlines leftovers)
tokensWithWhiteRoom = addWhiteRoom tokens
cuts = flip
unfoldr
tokensWithWhiteRoom
\tokens →
if null tokens
then Nothing
else let (chunk, leftovers) = cut (\chunk → sum (fmap length chunk) <= 80) tokens in Just (concat chunk, leftovers)
shirt = unlines snowflakes <> unlines cuts
if shirt == cloth
then exitSuccess
else writeFile (replaceExtension target ".minified.hs") shirt