COMP[39]161 Concepts of Programming Languages
Semester 2, 2018

Code (Week 2)

Note: This code was written in the second hour on Thursday and is therefore not examinable. You may still find it useful to elucidate concepts from the first hour on Thursday.

module Arith where 
import Data.Char
data Token = IntLit Int | LParen | RParen | Times | Plus | Unknown 
           deriving (Show)
lexer :: String -> [Token]
lexer (c:cs) | isSpace c = lexer cs 
             | c == '('  = LParen : lexer cs 
             | c == ')'  = RParen : lexer cs 
             | c == '*'  = Times  : lexer cs 
             | c == '+'  = Plus   : lexer cs 
             | isDigit c = let 
                (digits,rest) = span isDigit (c:cs)
               in IntLit (read digits) : lexer rest 
             | otherwise = Unknown : lexer cs 
lexer [] = []

sexp :: [Token] -> (Bool, [Token])
sexp tokens = case pexp tokens of 
    (True, Plus : rest) -> sexp rest
    (True, rest) -> (True, rest)
    (False, rest) -> (False, rest) 
pexp :: [Token] -> (Bool, [Token])
pexp tokens = case atom tokens of 
    (True, Times : rest) -> pexp rest
    (True, rest) -> (True, rest)
    (False, rest) -> (False, rest) 

atom :: [Token] -> (Bool, [Token])
atom (IntLit i : rest) = (True, rest)
atom (LParen : rest) = case sexp rest of 
    (True, RParen : rest') -> (True, rest')
    (_, rest') -> (False, rest')
atom rest = (False, rest)    

overall :: String -> Bool 
overall string = let (b, rest) = sexp (lexer string) 
                  in b && null rest

The rules being implemented here can be found in the Thursday Slides.

2018-11-16 Fri 19:37

Announcements RSS