[Haskell-beginners] Indenting

Daniel Fischer daniel.is.fischer at web.de
Sat Dec 5 16:09:42 EST 2009


Am Samstag 05 Dezember 2009 21:09:01 schrieb Brent Yorgey:
> If, on the other hand, you want the indentation to correspond to how
> "deep" within the expression the evaluation is taking place, then you
> can recursively pass along an extra parameter to your evaluation
> function, like so:
>
>   eval :: Dict -> Expression -> ([String], Double)
>   eval d e = evalIndented 0 d e where
>     evalIndented i d (Val x) = ([], x)
>     evalIndented i d (Add x y) =
>       let (tx, vx) = evalIndented (i+1) d x
>           (ty, vy) = evalIndented (i+1) d y
>       in  (replicate i ' ' ++ "Add " ++ show vx ++ " and " ++ show vy, vx +
> vy)
>
> ...and so on.

I would even suggest

eval :: Dict -> Expression -> ([(Int,String)],Double)
eval d e = evalIndented 0 d e
      where
        evalIndented _ _ (Val x) = ([],x)
        evalIndented i d (Add x y) =
            let ...
            in ((i,"Add " ++ show vx ++ " and " ++ show vy):tx ++ ty, vx + vy)
        ...

then you can easily extract the traces of subexpressions at a given depth and print those 
with adjusted indentation and change indentation schemes (indent two/four spaces further 
per level).



More information about the Beginners mailing list