Check out a free preview of the full Introduction to Elm, v2 course

The "Pure Functions" Lesson is part of the full, Introduction to Elm, v2 course featured in this preview video. Here's what you'd learn in this lesson:

Every Elm function is a pure function. Richard explains that, because of this, Elm has managed effects instead of side effects. - all of the clip


Transcript from the "Pure Functions" Lesson

>> Richard Feldman: Now, another function guarantee that we have in Elm besides same arguments, same results, is no side effects. Which is to say, whenever you run an Elm function, it's not allowed to modify any external state. It can't, all it can do is return a value, that's it. And that's all it can do.

So an example that would sort of violate this rule while satisfying the first rule is a fire-and-forget HTTP POST. So let's say I run a function in JavaScript that says, you know what? If you give me the same arguments, I'm always going to do the same HTTP post.

But I'm still gonna fire it off. I'm gonna send it off to the server and that's gonna modify the external state that's on the server, like the database. Something's gonna change, but hey, the function, same argument, same result. It just sort of sneakily did this other thing at the same time.

So in Elm, that's not allowed. You cannot do side effects inside Elm functions. So even though this satisfies the first function guarantee of same arguments, same result, it does not satisfy the second one. And all Elm functions have to satisfy both. Okay, so instead of doing side effects, Elm does what's known as managed effects.

Which is to say that any side effects have to be done through commands. All you can do in any Elm function that you write, is you can say, yeah, I want to give you back a description of commands that I want to run, or side effects that I want to have happen.

But the run time is going to perform them. Which means that any Elm function you call, is going to be a pure function, guaranteed. The entire language, everything we've been doing the entire day has been all pure functions. And that's going to continue throughout the rest of the workshop and the entire advanced workshop, because that's the only type of functions that Elm supports.

All of these side affecting stuff, all the stuff where you get different values depending on context all of that is isolated to the runtime and completely separate from stuff we do as Elm programmers.

Learn Straight from the Experts Who Shape the Modern Web

  • In-depth Courses
  • Industry Leading Experts
  • Learning Paths
  • Live Interactive Workshops
Get Unlimited Access Now