Back to Functional Programming Purity

3200587025_f4d7c94c71_zGot the itch to start studying Haskell again. Best to scratch it. I’m a bit sick of gluing together bits of Javascript code that don’t look like they should be together in the same script, then wondering why in the world it works. Granted, I did enjoy coding everything in the cloud, and my ultimate hope is for the same treatment be given to Haskell.

I keep getting drawn to Haskell’s simplicity, consistency, structural elegance, and perfect typing system, even though it still causes me a great deal of mental strain to understand it. And I found that after being away from it for several months, even the simplest concepts have to be re-learned.

So I did two things. One, I began re-reading Haskell guides like “Real World Haskell” and “Learn you a Haskell for Great Good!“. There are tons of very helpful resources online.

The second thing I did is to give “Programming Praxis” a try. In the past I used Project Euler, but having solved 108+ problems, I’m getting tired of the same old, same old. I’m sure I’ll get to the same point with Praxis, but for now its giving me a change.

Praxis 1 – Create a RPN calculator:
Loved my HP 48sx+ calculator in Engineering. Sad day when it kak’d. Still have trouble using regular algebraic calculators. So this one was is right up my alley. Lots of sample code online, but I started noticing that most code used function composition, rather than using variables. Up until now I always avoided function composition, but it really does make things clearer.

import Data.List

solveRPN :: String -> Float  
solveRPN = head . foldl calcme [] . words  
        calcme (x:y:ys) "*" = (x * y):ys  
        calcme (x:y:ys) "+" = (x + y):ys  
        calcme (x:y:ys) "-" = (y - x):ys  
        calcme (x:y:ys) "/" = (y / x):ys  
        calcme xs numStr = read numStr:xs  

main = do
    putStrLn "Enter calculation: "  
    input <- getLine
    putStrLn $ "Result = " ++ (show $ solveRPN input)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s