-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEncoding.hs
53 lines (41 loc) · 1.16 KB
/
Encoding.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
module Encoding
( encode
, decode
, countLambda
, toInteg
, toInt
, toPrint
, toList
, toChar
) where
---- Format Import
import Data.List
---- Handling Import
import Data.Maybe
---- Language Import
import AST
toPrint :: String -> Bλ
toPrint s = Unl $ pr ++ '.' : intersperse '.' s ++ "i"
where pr = replicate (length s) '`'
toList :: [Bλ] -> Bλ
toList = foldr cons nil
where cons a b = Fun "cons" [a, b]
nil = Fun "nil" []
encode :: (a -> Int) -> a -> Bλ
encode f c = Abs . Abs $ iterate (App True (Idx 1)) (Idx 0) !! f c
decode :: Bλ -> Maybe Int
decode (Abs (Abs (Idx 0))) = Just 0
decode (App _ (Idx 1) (Idx 0)) = Just 1
decode (Abs λ) = decode λ
decode (App _ (Idx 1) r) = fmap (+1) (decode r)
decode _ = Nothing
countLambda :: Bλ -> Integer
countLambda (App _ l r) = countLambda l + countLambda r
countLambda (Abs b) = 1 + countLambda b
countLambda _ = 0
toInteg :: String -> Integer
toInteg = read
toInt :: String -> Int
toInt = read
toChar :: Integer -> Char
toChar = toEnum . fromInteger