Search code examples
type-conversionpurescript

How exactly does operator <> work in Purescript?


Being new to Purescript, I am struggling to figure out why the following code (taken from "PureScript By Example") works as it does:

> flip (\n s -> show n <> s) "Ten" 10
"10Ten"

This makes sense to me: flip calls its first argument (the lambda expression) with its second and third argument in reverse order and so produces the concatenated string.

But I wonder why we get the following response with this snippet:

> flip (\n s -> show n <> s) 10 "Ten"

Could not match type Int with type String

Here is my line of thinking: operator <> which is actually a shorthand for Data.Semigroup.append is called with n deduced to String (an instance of Data.Semigroup) and s deduced to Int. So why can't <> append an Int to a String ? (I suppose because of it being right-associative, but am unsure ...)


Solution

  • To be clear...

    flip (\n s -> show n <> s) "Ten" 10  == show 10 <> "Ten"
    flip (\n s -> show n <> s) 10 "Ten"  == show "Ten" <> 10
    

    (<>) (an alias for Data.Semigroup.append) has the type:

    append :: a -> a -> a
    

    That is, it's arguments must be of the same type (they must match). But in your second call you're passing it a String and an Int, hence the type error.

    This behaviour might be surprising if you're coming from a weakly typed language like javascript with implicit type coercion.