# Type Classes in Elm (sort of)

**URL:** <https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354>\
**Category:** Show and Tell\
**Created:** [April 27, 2022, 7:05pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354 "2022-04-27T19:05:50Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [April 27, 2022, 7:05pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/1 "2022-04-27T19:05:50Z")

</div>

Hi there,

Here are two files: StringWriter.elm and CmdWriter.elm. (edit: links no longer work)

Both are implementations of the Writer monad. In particular, lets look at the two implementations of `andThen`:

```elm
andThen : (state1 -> StringWriter state2 ) -> StringWriter state1 -> StringWriter state2 
andThen fun ( a, out ) =
    let
        ( newA, newOut ) =
            fun a
    in
    ( newA
    , out |> (\c1 c2 -> c2 ++ c1) newOut
    )

```

```elm
andThen : (state1 -> CmdWriter state2 out) -> CmdWriter state1 out -> CmdWriter state2 out
andThen fun ( a, out ) =
    let
        ( newA, newOut ) =
            fun a
    in
    ( newA
    , out |> (\c1 c2 -> Cmd.batch [c1,c2]) newOut
    )

```

As you can see, we are using `c2 ++ c1` for the StringWriter and `Cmd.batch [c1,c2]` for the CmdWriter. Additionally, CmdWriter has two type variables, whereas StringWriter has just one. Other than that, the two implementations are identical.

**This is done by generating Elm files from templates using a little program**

Here is the input that generated the two files:

```auto
{
  "generateInto": "elm-gen/generated",
  "templatesFrom": "elm-gen/templates",
  "moduleBase": "Gen",
  "modules": {
    "StringWriter": {
      "Writer": {
        "imports": [],
        "output": {
          "type": "String",
          "polymorphic": false,
          "empty": "\"\"",
          "append": "(\\c1 c2 -> c2 ++ c1)"
        }
      }
    },
    "CmdWriter": {
      "Writer": {
        "imports": [],
        "output": {
          "type": "Cmd",
          "polymorphic": true,
          "empty": "Cmd.none",
          "append": "(\\c1 c2 -> Cmd.batch [c1,c2])"
        }
      }
    }
  }
}

```

Isn’t this awesome? 🤩

* * *

This project is actually just a few hours old, but the things that can be done with this…  
I mean, the writer monad is just a showstopper. The real value behind this tool comes from the [Enum](https://github.com/Orasund/elm-pen/blob/master/src/cli/templates/Enum.elm) and [Record](https://github.com/Orasund/elm-pen/blob/master/src/cli/templates/Record.elm) templates.

It will properly take a month or so until I can bring this tool into an alpha stage and officially announce it. But for now, I just wanted to share my excitement with you. 🙈 🙉 🙊

---

<div class="post-metadata">

**Author:** ![allanderek](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/allanderek/32/1360_2.png) [@allanderek](https://discourse.elm-lang.org/u/allanderek)\
**Post date:** [April 28, 2022, 8:42am UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/2 "2022-04-28T08:42:56Z")

</div>

You are doing a very similar thing to what I describe in [SimulatedHttp, functors and sed | Pole prediction dev blog](http://blog.poleprediction.com/posts/2022-03-11-poor-persons-functors/) though in a much more formal manner.  
Basically I see this as more like O’caml style functors than type classes, but it is towards the same end.  
I think the use-case I describe in the post (elm-program-test and HTTP) would be a good use-case for your developing tool.

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [April 28, 2022, 1:14pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/3 "2022-04-28T13:14:15Z")

</div>

Yeah you are right, the idea is the same. Though the key difference is that your solution takes an existing module as an input and clones it.

My solution takes json as input and creates new files from an existing template (using Handlebars.js). So my programm can’t actually handle your problem.

---

<div class="post-metadata">

**Author:** ![allanderek](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/allanderek/32/1360_2.png) [@allanderek](https://discourse.elm-lang.org/u/allanderek)\
**Post date:** [April 28, 2022, 2:53pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/4 "2022-04-28T14:53:20Z")

</div>

I’m not quite sure I understand why your tool couldn’t handle the problem I described? I think what you’re saying is that you couldn’t take an existing module and clone and then change the parts necessary. But that’s not necessary to solve the problem I was addressing.

I could just as easily use your approach. The only reason I didn’t use the ‘template’ approach is because the templates in my problem are quite complex **and** likely to change. That is, you’re going to be actively developing them, rather than your writer monads which are more of the kind “write once and they basically remain unchanged thereafter”. Because a templating language is “not-quite-elm” it means your editor plug-ins and possibly elm-format might not work. That’s a pain if you’re actively developing the template, but perfectly okay if you write it once and then can forget about it.

Having a template language is certainly “cleaner” and shows intent more explicitly. If it were successful enough, editor plug-ins and elm-format could be modified/augmented/branched to allow for such templates.

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [April 28, 2022, 5:29pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/5 "2022-04-28T17:29:57Z")

</div>

Im not quite sure with that. Yes, elm-format could be updated. But i bet, you can’t modify the elm-language-server to support templates, as they break any type system. So updating the template during development is something that i would not recommend.

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [May 2, 2022, 4:06am UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/6 "2022-05-02T04:06:40Z")

</div>

The project is now in Alpha.

You can find the repository here: [Orasund/elm-pen](https://github.com/Orasund/elm-pen) and the documentation [here](https://orasund.github.io/elm-pen/).

---

<div class="post-metadata">

**Author:** ![ursi](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/ursi/32/3166_2.png) [@ursi](https://discourse.elm-lang.org/u/ursi)\
**Post date:** [May 3, 2022, 10:19pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/7 "2022-05-03T22:19:51Z")

</div>

If type classes are something that gets you excited, can I ask why you are still using elm?

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [May 4, 2022, 6:20am UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/8 "2022-05-04T06:20:47Z")

</div>

Good question 🤣

I really LOVE elm. So it’s not like I would move over to Haskell just for type classes.  
Instead, it seems for me the obvious solution is to add the needed functionality to elm.

---

<div class="post-metadata">

**Author:** ![dta](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/dta/32/1917_2.png) [@dta](https://discourse.elm-lang.org/u/dta)\
**Post date:** [May 4, 2022, 8:20am UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/9 "2022-05-04T08:20:39Z")

</div>

I still don’t understand why this is considered “needed functionality”. You can already achieve the desired effect by writing the generated elm files, and indeed the generated files are smaller than the templates that generate them!

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [May 4, 2022, 11:14am UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/10 "2022-05-04T11:14:29Z")

</div>

You could ask the same question for polymorphic types (like `List a`).

Why do we need a `map:(a->b) -> List a -> List b` if we could simple write

- `mapIntToFloat:(Int->Float) -> List Int -> List Float`
- `mapFloatToInt:(Float->Int) -> List Float -> List Int`
- `mapFloatToFloat:(Float->Float) -> List Float -> List Float`
- `mapIntToInt:(Int->Int) -> List Int -> List Int`

The answer is quite simple: It is **faster** to write the implementation once and then just replace `a` and `b` with the needed types.

* * *

The same is with my Record template. I can write a function

```auto
map{{fieldName}}: ({{fieldType}} -> {{fieldType}}) -> {{record}} -> {{record}}
map{{fieldName}} fun record =
  { record | {{fieldName}} = fun record.{{fieldName}} }

```

and replace `{{fieldName}}`, `{{fieldType}}` and `{{record}}` with any combination of field and record. (like `time`, `Posix` and `{ time : Posix }`)

* * *

Hope this makes things clearer.

---

<div class="post-metadata">

**Author:** ![Carsten\_Konig](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/carsten_konig/32/4063_2.png) [@Carsten\_Konig](https://discourse.elm-lang.org/u/Carsten_Konig)\
**Post date:** [May 4, 2022, 12:11pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/11 "2022-05-04T12:11:57Z")

</div>

There is PureScript 😉

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [May 4, 2022, 12:18pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/12 "2022-05-04T12:18:15Z")

</div>

Yeah, and Scala and many other interesting languages. Some have Type Classes, some have other interesting ways of solving this problem.

But I am primarily interested in Elm.

---

<div class="post-metadata">

**Author:** ![Carsten\_Konig](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/carsten_konig/32/4063_2.png) [@Carsten\_Konig](https://discourse.elm-lang.org/u/Carsten_Konig)\
**Post date:** [May 4, 2022, 12:28pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/13 "2022-05-04T12:28:45Z")

</div>

I actually find your approach quite impressive and I really love to see how creative this community is when it comes to deal with “limitations” like this.

Due to some subjective dislike I’d rather not opt in into external code-generators (it took me a long while to give elm-spa a chance and I still have mixed feelings). Although I guess it’s a mild one here (as you probably would opt to check in the generated modules and not use the generator in CI etc.)

Who knows - maybe Evan likes this idea and someday it gets first-class support.

For the most parts you are right - I guess Elm does not really need type-classes - if only it would not have them semi-implemented (comparable and stuff).  
As it is right now dictionaries etc. are really a pain if you like to use domain-value-objects.

* * *

BTW: It’s totally fine that you want to stick with Elm - it’s a great language. But in case you or somebody else who really want this type of ad-hoc polymorphism - do yourself a favour and at least take a look at PureScript - for me it sits in the golden middle between Haskell and Elm - it has “sane” records, a great FFI and many of the features people coming from Haskell tend to miss in Elm (like type-classes, higher-kinded types)  
Of course it has it’s trade-offs and is arguably worse than Elm (generated size, performance, community-size, errors) - but It’s worth a look IMHO

---

<div class="post-metadata">

**Author:** ![dta](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/dta/32/1917_2.png) [@dta](https://discourse.elm-lang.org/u/dta)\
**Post date:** [May 4, 2022, 1:06pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/14 "2022-05-04T13:06:27Z")

</div>

Thanks for the reply.

What I’m hung up on is that this can be written in plain elm like this:

```elm
andThen : (out -> out -> out) -> (state1 -> (state2, out)) -> (state1, out) -> (state2, out)
andThen append fun (a, out) =
    let
        ( newA, newOut ) =
            fun a
    in
    ( newA
    , out |> append newOut
    )

stringWriterAndThen = andThen (\c1 c2 -> c2 ++ c1)
cmdWriterAndThen = andThen (\c1 c2 -> Cmd.batch [c1, c2])

```

What value is the code generator adding?

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [May 4, 2022, 1:27pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/15 "2022-05-04T13:27:46Z")

</div>

```auto
stringWriterAndThen = andThen (\c1 c2 -> c2 ++ c1)
cmdWriterAndThen = andThen (\c1 c2 -> Cmd.batch [c1, c2])

```

That’s exactly the point. You have to manually add new functions just to provide the append method.

You could of course add the append method to your type

```auto
type alias Appendable a =
  { content = a
  | append = a -> a -> a
  }

```

But the same trick does not work for the `andThen` function or the `map` function:

```auto
type alias Monad t =
  { content = t
  , andThen : (a -> b) -> Monad a -> Monad b
  , empty : t
  }

```

`a` and `b` need to be annotated as well, but that just turns into a loop (you now need to add 4 new variables to the andThen function, these need to be annotated again, so add 8 more variables to… you get the point).

* * *

So in conclusion, we can’t write a monad. But with Elm-Pen you now can. You can just provide all the function where you need `andThen` and the generator can replace it for you.

---

<div class="post-metadata">

**Author:** ![dta](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/dta/32/1917_2.png) [@dta](https://discourse.elm-lang.org/u/dta)\
**Post date:** [May 4, 2022, 1:51pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/16 "2022-05-04T13:51:26Z")

</div>

Is this different than what you’re trying to accomplish?

```elm
type alias Writer out emptyA andThenA andThenB =
    { empty : emptyA -> ( emptyA, out )
    , andThen : (andThenA -> ( andThenB, out )) -> ( andThenA, out ) -> ( andThenB, out )
    }

writer : out -> (out -> out -> out) -> Writer out a b c
writer empty append =
    { andThen = andThen append
    , empty = \contents -> ( contents, empty )
    }

andThen : (out -> out -> out) -> (state1 -> ( state2, out )) -> ( state1, out ) -> ( state2, out )
andThen append fun ( a, out ) =
    let
        ( newA, newOut ) =
            fun a
    in
    ( newA
    , out |> append newOut
    )

stringWriter =
    writer "" (\c1 c2 -> c2 ++ c1)

cmdWriter =
    writer Cmd.none (\c1 c2 -> Cmd.batch [c1, c2])

{-| example
-}
output =
    stringWriter.empty 1
        |> stringWriter.andThen (\a -> ( a + 1, String.fromInt a ))
        |> stringWriter.andThen (\a -> ( a + 1, String.fromInt a ))
        |> Tuple.second

```

---

<div class="post-metadata">

**Author:** ![solificati](https://avatars.discourse-cdn.com/v4/letter/s/2bfe46/32.png) [@solificati](https://discourse.elm-lang.org/u/solificati)\
**Post date:** [May 4, 2022, 2:27pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/17 "2022-05-04T14:27:24Z")

</div>

Main usage of type classes comes from HKT. Then you can write your function that accepts any Writer and uses it’s functions but is not concerned with type inside Writer. Code generation can you get so far. If we ignore this use case, then “type classes” can be implemented with extensible records where some fields are just fields with closed over record.

---

<div class="post-metadata">

**Author:** ![Lucas\_Payr](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/lucas_payr/32/4993_2.png) [@Lucas\_Payr](https://discourse.elm-lang.org/u/Lucas_Payr)\
**Post date:** [May 4, 2022, 2:51pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/18 "2022-05-04T14:51:20Z")

</div>

First, thanks for your answer. It really got me thinking.

Second, your code works because you are specifying `springWriter` explicitly.

Your [code no longer complies](https://ellie-app.com/hpVZtvZmJF8a1) if you try to abstract away to an arbitary writer:

```auto
run w =
    w.empty 1
        |> Tuple.second
        |> Html.text

{-| example
-}
main =
    let
        _ = run cmdWriter
    in
    run stringWriter

```

So yes. You are right. For this explicit example, my solution would not be very elegant. And yes, I am actually very impressed how far one can come if one just looks at the functions separate of the type (I always tried to put both into the same record).

* * *

I still see the need for my tool, though. Maybe not for specifying a writer - and I might be removing this example in the final version of the tool - but for Enums, Records or any example where you actually generate a function with some generated logic in it.

---

<div class="post-metadata">

**Author:** ![dta](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/dta/32/1917_2.png) [@dta](https://discourse.elm-lang.org/u/dta)\
**Post date:** [May 4, 2022, 4:23pm UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/19 "2022-05-04T16:23:58Z")

</div>

This doesn’t compile because `Html.text` requires a string. This does compile:

```elm
run w =
    w.empty 1
        |> Tuple.second

main =
    let
        _ = run cmdWriter
    in
    run stringWriter
        |> Html.text

```

I was thinking more about what @solificati said, and I think the biggest limitation to my approach is that you need to pass the monad operations multiple times if you want to be able to operate on monads containing different types. For example, you need\[1\] to write:

```elm
doSomething writerOperations1 writerOperations2 writerOperations3 mapIntOut mapFloatOut =
    writerOperations1.empty 3
        |> writerOperations2.andThen (\a -> ( toFloat a, mapIntOut a ))
        |> writerOperations3.andThen (\a -> ( String.fromFloat a, mapFloatOut a ))
        |> Tuple.second

```

when it feels like you should be able to write:

```elm
doSomething writerOperations mapIntOut mapFloatOut =
    writerOperations.empty 3
        |> writerOperations.andThen (\a -> ( toFloat a, mapIntOut a ))
        |> writerOperations.andThen (\a -> ( String.fromFloat a, mapFloatOut a ))
        |> Tuple.second

```

* * *

1. I passed 3 values for the sake of example, but only two are strictly necessary here since the `empty` operation binds different type variables than the `andThen` operation.

---

<div class="post-metadata">

**Author:** ![ursi](https://yyz1.discourse-cdn.com/flex035/user_avatar/discourse.elm-lang.org/ursi/32/3166_2.png) [@ursi](https://discourse.elm-lang.org/u/ursi)\
**Post date:** [May 5, 2022, 12:45am UTC](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354/20 "2022-05-05T00:45:48Z")

</div>

+1 to this. I got my FP start in Elm, but when I decided to give PureScript a try, I ended up never looking back. I didn’t implement type classes like you @Lucas_Payr (frankly I didn’t even know about them at the time), but I did implement an FFI that was quite useful (and still works if anyone’s curious). It was really nice to move to a language that had these things already built in. Also fun fact that I realized relatively early on about PureScript that really solidified it for me: you can essentially build Elm within PureScript! Okay, plug over, bottom line, if you wanna go beyond what Elm gives you, give PureScript a try!

[Next page](https://discourse.elm-lang.org/t/type-classes-in-elm-sort-of/8354.md?page=2)
