[Haskell-beginners] Hutton Ex 8.9.5 & Ex 8.9.6

trent shipley trent.shipley at gmail.com
Fri Sep 14 08:04:12 UTC 2018


Pankaj Godbole's code examples for 8.9.6 are sufficiently more complex than
mine,that I am worried I missed an obvious bug I'm not experience enough to
know about or test for.

Correction or reassurances would be appreciated.

Regards,

Trent

{--

5. Given the type declaration

data Expr = Val Int | Add Expr Expr

define a higher-order function

folde :: (Int -> a) -> (a -> a -> a) -> Expr -> a

such that folde f g replaces each Val constructor in an expression by the
function f, and each Add constructor by the function g.

Hutton, Graham. Programming in Haskell (Kindle Locations 3364-3371).
Cambridge University Press. Kindle Edition.

--}

data Expr = Val Int | Add Expr Expr

-- Trent's stuff

folde :: (Int -> a) -> (a -> a -> a) -> Expr -> a
folde f g (Val x) = f x
folde f g (Add left right) = g (folde f g left) (folde f g right)

{--

6. Using folde, define a function

eval :: Expr -> Int

that evaluates an expression to an integer value, and a function

size :: Expr -> Int

that calculates the number of values in an expression.

Hutton, Graham. Programming in Haskell (Kindle Locations 3372-3374).
Cambridge University Press. Kindle Edition.

--}

-- Trent's stuff

eval :: Expr -> Int
eval = folde id (+)

size :: Expr -> Int
size = folde (\_ -> 1) (+) -- hlint suggests \_ as const 1

test0 :: Expr
test0 = Val 1

test1 :: Expr
test1 = Add (Val 1) (Val 2)

test3 :: Expr
test3 = Add (Val 1) (Add (Val 2) (Val 3))

-- the below are from:
-- Pankaj Godbole
-- https://github.com/pankajgodbole/hutton/blob/master/exercises.hs

evalE             :: Expr -> Int
evalE (Val n)     =  n
evalE (Add e1 e2) =  folde toEnum (+) (Add e1 e2)
-- doesn't a Val have to prefix an int?  Then why is f "toEnum"?


numVals             :: Expr -> Int
numVals (Val n)     =  1
numVals (Add e1 e2) =  numVals e1 + numVals e2
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.haskell.org/pipermail/beginners/attachments/20180914/e91e0a44/attachment.html>


More information about the Beginners mailing list