import Data.Char(isSpace,isNumber,isAlpha,isAlphaNum)
— This is an algebraic data type.
data Token =
Copyright By PowCoder代写 加微信 powcoder
Ident String — Ident is a type constructor,
— which given a String constructs a Token.
| LParen — LParen is a nullary type constructor,
— i.e., it’s a stand-alone Token.
deriving Show — tell Haskell to derive a way to convert Tokens to Strings
recogniseKwd :: String -> Token
recogniseKwd “return” = Return
recogniseKwd “if” = If
recogniseKwd s = Ident s
Lists are also algebraic datatypes with two constructors:
[] <-- empty list : (written in infix, pronounced "cons" : a -> [a] -> [a]
e.g. [1,2,3] is 1:2:3:[]
String is a type abbreviation for [Char]
type String = [Char]
lexer :: String -> [Token]
lexer [] = []
lexer (‘(‘:xs) = LParen : lexer xs
lexer (‘)’:xs) = RParen : lexer xs
lexer (‘{‘:xs) = LBrace : lexer xs
lexer (‘}’:xs) = RBrace : lexer xs
lexer (‘-‘:xs) = Minus : lexer xs
lexer (‘=’:xs) = Eq : lexer xs
lexer (‘>’:xs) = Gt : lexer xs
lexer (‘;’:xs) = Semi : lexer xs
lexer (x:xs)
| isSpace x = lexer xs
| isNumber x =
let (number,rest) = span isNumber (x:xs)
in Num(read number):lexer rest
| isAlpha x =
let (ident,rest) = span isAlphaNum (x:xs)
in recogniseKwd ident:lexer rest
| otherwise = error “Unrecognised token :(”
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com