Skip to content

Commit 2a30eea

Browse files
BodigrimBinderDavid
authored andcommitted
Add example from LYAH to GHC-39999
1 parent 62fb35e commit 2a30eea

File tree

3 files changed

+27
-0
lines changed

3 files changed

+27
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
main = print $ 5 + 4
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
main = print $ 5 + "4"
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
title: Adding numbers to strings
3+
order: 4
4+
---
5+
6+
## Error message
7+
8+
```
9+
Main.hs:1:16: error: [GHC-39999]
10+
• No instance for ‘Num String’ arising from the literal ‘5’
11+
• In the first argument of ‘(+)’, namely ‘5’
12+
In the second argument of ‘($)’, namely ‘5 + "4"’
13+
In the expression: print $ 5 + "4"
14+
|
15+
1 | main = print $ 5 + "4"
16+
| ^
17+
```
18+
19+
## Explanation
20+
21+
Given that Haskell is a strong statically typed language, it is not a surprise that adding numbers to strings gives a compile-time error. However, one could expect GHC to be unhappy about `"4"`, not about `5` as above! Let's take a deeper look on how the type checker works.
22+
23+
The compiler first encounters the operator `(+)` which has type `Num a => a -> a -> a`. Thus it infers that both arguments of `(+)` should be of the same type `a`. Looking at the first argument `5` does not reveal us what `a` is: it could be `Int`, could be `Double`, etc. But the second argument `4` is certainly `String`, so the compiler concludes that `a` should be `String`.
24+
25+
Now the compiler looks again at the first argument `5`. Since the second argument of `(+)` is `String`, it infers that `5` must be `String` as well. In Haskell a numeric literal could be anything which has `instance Num`, so GHC searches for `instance Num String` but could not find one and bails out with an error.

0 commit comments

Comments
 (0)