Introduction to Elm, v2

Anonymous Functions

Richard Feldman

Richard Feldman

Vendr, Inc.
Introduction to Elm, v2

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

The "Anonymous 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:

Richard gives an example of an anonymous function defined inline with a slightly different syntax from named functions. - whole clip


Transcript from the "Anonymous Functions" Lesson

>> Richard Feldman: So here's the equivalent Elm code, this also introduces something new that we haven't seen before. So \str arrow, we'll get into what that means momentarily. String.toUpper str, so String.toUpper is Elm's equivalent of .toUpperCase in JavaScript. We've seen ++ and then of course we've seen lists. So, this right here is an anonymous function.

This is how you define a function in line in Elm without giving it a name. Like we did previously with pluralize. So syntactically, what's going on here is, this little \ is intended to look like a lambda. So lambda is usually the term for functions in a lot of programming languages, and the history of functions in general in math.

So that's why the backslash is there. It's intended to look like a little lambda sign, as sort of a historical nod. We got an arrow, which indicates the end of the argument list and the beginning of the function implementation. So, in JavaScript, you have the double equals arrow, or the fat arrow.

In Elm, it's just a small arrow with a dash instead of an equal sign. Also, if we had multiple arguments here, those would be separated by spaces, just like in a named function, with no commas. This is going to uppercase the string. That's going to add an exclamation point on the end.

And if we run this, we're gonna get the same thing that we did with the other implementation, POW!, ZAP!, BLAM!. With exclamation points and uppercase. If we tried to make the same mistake as before. We tried to add 500 on there, it's just not gonna compile. We're gonna get this error message at compile time.

The third and fourth entries in this list are different types of values. Hint, every entry in a list needs to be the same type of value. So this will not compile, that's one of the ways that Elm avoids this particular type of runtime exception.

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