Last active
November 8, 2020 20:11
-
-
Save i-am-tom/d2be4384a7b4cc6283be5097df12c63c to your computer and use it in GitHub Desktop.
Code playground for http://www.tomharding.me/2016/10/29/peano-forte/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Main where | |
import Prelude | |
import Effect.Console (logShow) | |
import TryPureScript (render, withConsole) | |
-- Declare the recursive type. | |
data Peano = Z | S Peano | |
-- This allows us to print the type. | |
instance showPeano :: Show Peano where | |
show Z = "Z" | |
show (S x) = "(S " <> show x <> ")" | |
-- So we can use "==" with Peanos. | |
instance eqPeano :: Eq Peano where | |
eq Z Z = true | |
eq (S x) (S y) = x == y | |
eq _ _ = false | |
-- So we can use "+" and "*". | |
instance semiringPeano :: Semiring Peano where | |
add Z y = y | |
add x Z = x | |
add (S x) y = S (x + y) | |
mul Z y = Z | |
mul x Z = Z | |
mul (S x) y = y + mul x y | |
one = S Z | |
zero = Z | |
-- For ease of debugging. | |
toInt :: Peano -> Int | |
toInt Z = 0 | |
toInt (S x) = 1 + toInt x | |
-- The three examples from the article. | |
main = render <=< withConsole $ do | |
logShow $ (S (S Z)) == (S (S (S Z))) | |
logShow $ (S (S (S Z))) + (S (S Z)) | |
logShow $ toInt (S (S (S Z))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment