Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson

Already subscribed? Sign In


    Define an Infix Operator for the apply Function in Elm

    Enrico BuonannoEnrico Buonanno

    Elm allows you to write terse code by defining your own infix operators. It's common to do this for the apply function of applicatives (some Elm packages call it andMap instead of apply).

    In this lesson you see how this is done and how this benefits your code as a result.



    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson


    Instructor: 00:01 This technique of defining of an apply function that performs function application where all the values are wrapped in some type, like our field type here, and as a result, effects of this type are compounded in a way.

    00:15 This is actually a classic functional programming technique, and it's called applicative. In jargon, you would say that our field is an applicative factor. The interesting effect is that we end up with a call to submit here that is very similar to a normal function call.

    00:31 In the normal function call, you would have submit, model.message, model.h. We just have to wrap the function into a valid and apply all these other arguments with the apply function.

    00:51 We can make this code look even more like than normal function application by defining an infix operator. In Elm, you can define infix operators if they're composed of special characters only.

    01:03 A symbol that is used for apply in functional languages like Haskell will be this, but more common in some Elm libraries, you will find this symbol. The type would be the same as here, but the arguments would be the other way around.

    01:20 Let me move this from here to here, and the definition will be as follows. We have an FF and an FA, and we rely on the previous implementation, apply FA FF. In fact, I can write this in a way that's even more concise.

    01:38 I can say "Flip apply," which yields a new function that is based on apply, but flips the order of the arguments. Now, we can change our code here and just use this symbol pie colon.

    01:50 You can see how my code has become a bit more concise still. Just to check that nothing has changed, if I type "Hello" in all fields and submit, we get validation errors as expected. If I fix these, then I get a successful request.