loading...

re: Explain Pure Functions Like I'm Five VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Just out of curiosity, how would you implement a pure function of console.log? I have no experience in functional languages.
 

Instead of executing the side-effects (e.g. calling a function log that returns a string), you create objects that represent those actions (e.g. calling a function log that returns a IO<string>).

You compose these "objects that represent actions" with other objects (usually with map/flatMap).

Once you're done composing all your effects, you bubble them up to main and use an escape hatch to trigger the execution of all side-effects at once (sometimes called unsafePerformIO). In Haskell, you don't use the escape hatch at all - you bubble up all IO<A> actions to main, and the runtime will go through your tree of effects and execute them. This is when things actually get "impure" - but you don't care anymore because it's now beyond the boundary of your application.

Here's a sample implementation of what IO<A> would look like in scala: scalafiddle.io/sf/AnXRGhf/8 (should be fairly easy to read regardless of your background, let me know if it's not and you'd like to see this in another language)

code of conduct - report abuse