Previous Up Next

Chapter 4  Tips and tricks

4.1  Irrefutable patterns

Irrefutable patterns on the RHS (VarParen.lg):
>  module VarParen where
>  import Result
> 
>  newtype Tree                  =  Node [Tree]
>                                   deriving (Show)
> 
>  %{
> 
>  Terminal                      =  '(' | ')';
> 
>  Nonterminal                   =  paren {Tree};
> 
>  paren  {Node []}              :  ;
>         {Node (x : xs)}        |  paren {x}, '(', paren {Node xs}, ')';
> 
>  }%
> 
>  frown ts                      =  fail "syntax error"



4.2  Inherited attributes

Shows how to simulate inherited attributes: expr has type Integer -> (Tree Integer, Integer), it takes the global minimum to the rep-min tree (with all elements replaced by the minimum) and the local minimum (RepMin.lg).
>  module RepMin where
> 
>  data Tree a    =  Leaf a | Fork (Tree a) (Tree a)
>                    deriving (Show)
> 
>  data Terminal  =  Num Integer | LPar | RPar
> 
>  %{
> 
>  Terminal      =  Num {Integer}
>                |  LPar  as "("
>                |  RPar  as ")";
> 
>  Nonterminal   =  *  start  {Tree Integer}
>                |     expr   {Integer -> (Tree Integer, Integer)};
> 
>  start { let (t, m) = f m in t }
>    : expr {f};
> 
>  expr { \ m -> (Leaf m, i) }
>    :  Num {i};
>  expr { \ m -> let  { (tl, ml)  =  l m
>                     ; (tr, mr)  =  r m }
>                in (Fork tl tr, ml `min` mr) }
>    :  expr {l}, "(", expr {r}, ")";
> 
>  }%
> 
>  frown ts                      =  fail "syntax error"

!avoid layout-sensitive code!

4.3  Dealing with conflicts

>  many' x : many x;

4.4  Multiple attributes


Previous Up Next