Haskell Parameter Pattern Matching -
i trying create complier using haskell part of university coursework.
i want create method matches string this:
int = 5 int foo = 3
so method created:
readinstruction :: string -> string readinstruction ( 'i' : 'n' : 't' : ' ' : varname : ' ' : '=' : ' ' : val : []) = "declare int " ++ [varname] ++ " = " ++ [val]
however works variable names of 1 letter. please help. how should this?
also side note, noticed next not compile:
readinstruction ( "int " ++ varname ++ " = " ++ val ) = "declare int " ++ varname ++ " = " ++ val
why?
please note: i'm new haskell , know basics. don't know other library functions , prefer not utilize them (as have been discouraged utilize them coursework).
when you're pattern matching, can pattern match on constructors. lists, 2 constructors :
, []
, whereas ++
function on lists. compiler can't work backwards function application, can constructor application (a special kind of function lives in own namespace in haskell).
a much improve alternative tokenize input, prevent errors having insufficient patterns, , much easier process in long run. particularly since you're wanting write compiler, should utilize tokenizer pretty much accepted way write parsers. instead have
-- simple tokenizer, splits on whitespace -- `int x=1` won't tokenized correctly tokenize :: string -> [string] tokenize = words readinstructions :: [string] -> (string, [string]) readinstructions ("int" : varname : "=" : val : rest) = ("declare int" ++ varname ++ " = " ++ val, rest) readinstructions otherpatterns = undefined
the reason why homecoming (string, [string])
iteratively apply readinstructions
, have consume number of tokens needs each command. do
main = programme <- readfile "myprogram.prog" allow tokens = tokenize programme (firstinstr, tokens') = readinstructions tokens (secondinstr, tokens'') = readinstructions tokens' putstrln firstinstr putstrln secondinstr
if think looks laborious, you'd correct. because there much improve ways of handling sort of thing in haskell, , quite elegantly too. 1 time you've completed assignment, encourage @ parsec library, , state monad. parsec library has lot of work done in terms of writing tokenizer , turning tokens meaningful, , state monad library built on top of. having understanding of state monad help haskell programmer in general, used lot many different problems.
haskell pattern-matching
No comments:
Post a Comment