-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBF.hs
More file actions
38 lines (32 loc) · 1.16 KB
/
Copy pathBF.hs
File metadata and controls
38 lines (32 loc) · 1.16 KB
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
{-# LANGUAGE NoImplicitPrelude #-}
module BF where
import Prelude(Show(..),(++),concat,map,(.),($),String)
data Command = Plus | Minus | ShiftL | ShiftR | Out | In | Loop Program
instance Show Command where
show Plus = "+"
show Minus = "-"
show ShiftL = "<"
show ShiftR = ">"
show Out = "."
show In = ","
show (Loop p) = "[" ++ (concat . (map show) $ p) ++ "]"
type Program = [Command]
print :: Program -> String
print = concat . (map show)
optimize :: Program -> Program
optimize [] = []
optimize (Out:xs) = Out:(optimize xs)
optimize (In:xs) = In:(optimize xs)
optimize ((Loop p) : xs) = (Loop (optimize p)) : (optimize xs)
optimize (Plus:xs) = plus (optimize xs) where
plus (Minus:ys) = ys
plus ys2 = Plus:ys2
optimize (Minus:xs) = minus (optimize xs) where
minus (Plus:ys) = ys
minus ys2 = Minus:ys2
optimize (ShiftL:xs) = left (optimize xs) where
left (ShiftR:ys) = ys
left ys2 = ShiftL:ys2
optimize (ShiftR:xs) = right (optimize xs) where
right (ShiftL:ys) = ys
right ys2 = ShiftR:ys2