min_2_max
min_2_max

Reputation: 13

Using anonymous functions in Haskell

I am reading Get Programming with Haskell to gain an understanding of functional programming. In Lesson 10, the author discusses using functional programming to create simple objects using closures. Up to this point in the book, the topics have included higher order functions, lambda functions, and closures.

He describes something along the lines of:

simpleObject intAttribute= \message -> message intAttribute

simpleObject returns a closure which in effects stores the intAttribute. The closure takes a function as an argument and supplies the intAttribute as the parameter. For example (mine):

obj = simpleObject 5
doubleIt x = 2 * x
obj doubleIt (returns 10)

I think I am pretty clear up to this point.

The author then describes an accessor similar to:

getAttribute y = y (\x -> x)
getAtrribute obj (returns 5)

The code works as expected returning the captured intAttribute. This is where I get lost. How does the getAttribute code work?

Upvotes: 1

Views: 374

Answers (1)

chi
chi

Reputation: 116174

We can evaluate the expression substituting each defined identifier with its own definition.

getAtrribute obj
= { def. getAttribute }
obj (\x -> x)
= { def. obj. }
simpleObject 5 (\x -> x)
= { def. simpleObject }
(\message -> message 5) (\x -> x)
= { beta reduction }
(\x -> x) 5
= { beta reduction }
5

Upvotes: 2

Related Questions