[Haskell-cafe] String to binary tree

Thorkil Naur naur at post11.tele.dk
Tue May 30 11:51:21 EDT 2006


Hello,

Both my Hugs and my GHCi report a type error when presented with this. A 
possible repaired version looks like this:

  calc :: String -> Float
  calc = g . foldl f [] . words
    where
      f (x:y:zs) "+" = y+x:zs
      f (x:y:zs) "-" = y-x:zs
      f (x:y:zs) "*" = y*x:zs
      f (x:y:zs) "/" = y/x:zs
      f xs y = read y : xs
      g [r] = r

Not as small, but still quite nice.

Regards
Thorkil
On Tuesday 30 May 2006 15:10, Sebastian Sylvan wrote:
> A bit OT perhaps, but I'd just like to point out this wonderful little
> code snippet from the Haskell wiki-page that I've always liked, in
> case nobody's seen it:
> 
> calc :: String -> Float
> calc = foldl f [] . words
>   where
>     f (x:y:zs) "+" = y+x:zs
>     f (x:y:zs) "-" = y-x:zs
>     f (x:y:zs) "*" = y*x:zs
>     f (x:y:zs) "/" = y/x:zs
>     f xs y = read y : xs
> 
> That's it. An RPN evaluator in a couple of lines.


More information about the Haskell-Cafe mailing list