Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Elm use the '++' operator to concatenate strings?

I am learning Elm and I find a lot of things that are attractive about it, such as its elegance and simplicity. However, one aspect that I find puzzling is its use of "++" to concatenate strings. For example:

> "hello" ++ " world"
"hello world"

Addition works the way you would expect it.

> 2 + 3 + 9
14

The majority of high level languages such as C#/Java/JavaScript/Python use a single plus "+" in concatenating strings in the analogous way multiple numbers would be summed. It seems so much more intuitive, as there is a certain consistency in concatenating strings like summing numbers.

Does anyone know the logic behind the design decision to use a ++ instead of + in this context?

like image 516
Dave S Avatar asked Feb 23 '17 13:02

Dave S


1 Answers

Elm allows you to define polymorphic functions.

Parametric polymorphism is when a function can be applied to elements of any types:

f : (a, b) -> (b, a)
f (x, y) = (y, x)

Ad-hoc polymorphism is when a function can be applied to elements of some types:

g : appendable -> appendable -> appendable -> appendable
g x y z = x ++ y ++ z

h : number -> number -> number
h x y = (x + 2) * y

The type variables number and appendable are special because they represent a subset of all Elm types. List and String are appendable types while Float and Int are number types.

It could theoretically be possible to instead define a hasPlus type variable which would include List, String, Float and Int, but then when defining a polymorphic function you would need to be aware that it is possible that x + y is different than y + x and that would be quite a burden if you are actually thinking about numbers...

like image 119
Zimm i48 Avatar answered Nov 23 '22 05:11

Zimm i48