1. Anton Golov
  2. Toy C#-ish compiler

Source

Toy C#-ish compiler / SymbolTable.hs

module SymbolTable (
    Table,
    SymbolTable.empty,
    SymbolTable.withN,
    SymbolTable.lookup,
    SymbolTable.member,
    SymbolTable.insert,
    SymbolTable.insert',
    SymbolTable.ajs,
    SymbolTable.size,
) where

-- Where we define a convenient type to represent such tables, define some
-- functions to better operate on it, and finally get out of the mess we've been
-- working in.

import qualified Data.Map as M
import Control.Applicative
import Data.Maybe

data Table a = Table (M.Map String (a, Int)) Int deriving Show

empty :: Table a
empty = Table M.empty 0

withN :: Int -> Table a
withN = Table M.empty

lookup :: Show a => String -> Table a -> Maybe (a, Int)
lookup k (Table m _) = M.lookup k m

member :: String -> Table a -> Bool
member x (Table m _) = M.member x m

insert :: String -> a -> Table a -> Table a
insert k v (Table m i) = Table (M.insert k (v, i) m) $ i+1

insert' :: String -> a -> Table a -> Table a
insert' k v (Table m i) | M.member k m = Table m i
                        | otherwise = Table (M.insert k (v, i) m) $ i+1 

ajs :: Int -> Table a -> Table a
ajs x (Table m i) = Table m $ i+x

size :: Table a -> Int
size (Table _ i) = i