2 ms·
I'd disagree and say that it's value-level addition. Adding the number `3` to the number `5` gives us a single number `8`, not a pair of `3` and `5`. Likewise a
by chriswarbo 8y ago
I'd disagree and say that it's value-level addition. Adding the number `3` to the number `5` gives us a single number `8`, not a pair of `3` and `5`. Likewise appending `"hello "` to `"world"` gives us a single string `"hello world"` not a pair of strings.
If we model arithmetic addition with Peano numerals, that would be:
three = S (S (S Z))
five = S (S (S (S (S Z))))
eight = plus three five
= S (S (S (S (S (S (S (S Z)))))))
We can model strings as lists of characters (which Haskell does, but is inefficient). It's essentially the same except the second constructor takes a character as argument:
hello = Cons 'h' (Cons 'e' (Cons 'l' (Cons 'l' (Cons 'o' (Cons ' ' Nil)))))
world = Cons 'w' (Cons 'o' (Cons 'r' (Cons 'l' (Cons 'd' Nil))))
greet = append hello world
= Cons 'h' (Cons 'e' (Cons 'l' (Cons 'l' (Cons 'o' (Cons ' ' Cons 'w' (Cons 'o' (Cons 'r' (Cons 'l' (Cons 'd' Nil)))))))))
The algorithms for adding Peano numerals and appending lists of characters are identical:
plus Z y = y
plus (S x) y = S (plus x y)
append Nil y = y
append (Cons x xs) y = Cons x (append xs y)
If we replace 'Char' with '()' (i.e. `List ()` or `[()`]) then they're isomorphic.
I wrote up some thoughts about this connection at http://chriswarbo.net/blog/2014-12-04-Nat_like_types.html http://chriswarbo.net/blog/2014-12-04-Nat_like_types.html