Skip to content

Instantly share code, notes, and snippets.

@i-am-tom
Last active November 8, 2020 20:11
Show Gist options
  • Save i-am-tom/d2be4384a7b4cc6283be5097df12c63c to your computer and use it in GitHub Desktop.
Save i-am-tom/d2be4384a7b4cc6283be5097df12c63c to your computer and use it in GitHub Desktop.
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