1

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?

4
  • 1
    getAtrribute obj == obj (\x -> x) == (simpleObject 5) (\x -> x) == (\message -> message 5) (\x -> x) == (\x -> x) 5 == 5 Commented Oct 31, 2018 at 0:09
  • Ahh...that helps a lot! I was getting hung up on the second to last transition. Thank you so much! Commented Oct 31, 2018 at 0:38
  • This is the second time I’ve seen this weird technique recently (first at stackoverflow.com/q/53023885/4942760 ). I think this specific case makes no sense at all. The only semi-sensical usage I can think of is a record of closures to either implement poor mans gadts (not necessary as gadts exist) or allowing some kind of oo like objects/interface (but why not use typeclasses?) This technique is no different from just using the value directly (isomorphism is ($id) in one way and flip ($) the other). What is this supposed to be useful for? Commented Oct 31, 2018 at 11:15
  • @DanRobertson I don't think it has any purpose, but it's merely an exercise about closures. Realizing that such isomorphism exists can also be another exercise. It's mostly about learning/understanding than being really useful on its own (IMO). Commented Oct 31, 2018 at 18:50

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! Commenter Alec posted above a similar technique which clarified the code also.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.