4 ms·
> imperative and side-effect programming (which often the most readable and understandable way to write code) Oh come on, at least provide a couple examples wi
by codygman 12y ago
> imperative and side-effect programming (which often the most readable and understandable way to write code)
Oh come on, at least provide a couple examples with a claim like that...
> One thing that I disliked about Haskell is that it can be a bit cumbersome to do imperative and side-effect programming
From a not quite yet ready to release everywhere web scraping library of mine in Haskell:
main = runScraper $ do
get "https://www.paypal.com/login"
postToForm (Name "login_form") (Just creds) AllVisible
get "https://www.paypal.com/myaccount/home"
cursor <- liftM (fromMaybe (error "Couldn't get cursor")) getCurrentCursor
liftIO . putStrLn $ "Your Paypal balance is: " <> getPaypalBalance cursor
where creds = [ ("login_email", "email@example.com") -- put your credentials here
, ("login_password", "password")]
An example of using lenses and imperative programming to create pong[0]:
-- Update the paddles
updatePaddles :: Float -> State Pong ()
updatePaddles time = do
p <- get
let paddleMovement = time * paddleSpeed
keyPressed key = p^.keys.contains (SpecialKey key)
-- Update the player's paddle based on keys
when (keyPressed KeyUp) $ paddle1 += paddleMovement
when (keyPressed KeyDown) $ paddle1 -= paddleMovement
-- Calculate the optimal position
let optimal = hitPos (p^.ballPos) (p^.ballSpeed)
acc = accuracy p
target = optimal * acc + (p^.ballPos._y) * (1 - acc)
dist = target - p^.paddle2
-- Move the CPU's paddle towards this optimal position as needed
when (abs dist > paddleHeight/3) $
case compare dist 0 of
GT -> paddle2 += paddleMovement
LT -> paddle2 -= paddleMovement
_ -> return ()
-- Make sure both paddles don't leave the playing area
paddle1 %= clamp (paddleHeight/2)
paddle2 %= clamp (paddleHeight/2)
From "Program imperatively using Haskell lenses"[1]:
battle :: StateT Game IO ()
battle = do
-- Charge!
forM_ ["Take that!", "and that!", "and that!"] $ \taunt -> do
lift $ putStrLn taunt
strike
-- The dragon awakes!
fireBreath (Point 0.5 1.5)
replicateM_ 3 $ do
-- The better part of valor
retreat
-- Boss chases them
zoom (boss.position) $ do
x += 10
y += 10
As for "which often the most readable and understandable way to write code"... let's find out! I'll trade some examples for common tasks if you'll do the same :)