I'm trying to write a function
toPeano :: Int -> Nat
toPeano n =
that turns an Integer into its Peano Number.
I have the data:
data Nat =
Zero |
Succ Nat
deriving Show
For example,
toPeano 0 = Zero
toPeano 1 = Succ Zero
toPeano 2 = Succ (Succ Zero)
and so on.
I have no idea how to get it to print out the Peano Numbers given an integer. I've never worked with Peano numbers so any help with this would be greatly appreciated!
Thank you!
Your question isn't clear, so I'll start from the conversion:
toPeano 0 = Zero
toPeano 1 = Succ Zero
toPeano 2 = Succ (Succ Zero)
This is rather explicit. You can define Peano numbers with a simple recursion and have that work for all naturals:
toPeano 0 = Zero
toPeano x
| x < 0 = error "Can not convert a negative number to Peano"
| otherwise = Succ (toPeano (x-1))
The core here is the Succ (toPeano (x-1))
- this just subtracts one from the integer and adds one to the Peano construction.
Now how about the other direction? Well, every time you see "Succ" you can just add one:
fromPeano Zero = 0
fromPeano (Succ x) = 1 + fromPeano x -- note this is inefficent but right now we don't care
Printing Results
Now the only part of what you said that looked like a question was:
I have no idea how to get it to print out the Peano Numbers given an integer.
This has nothing to do with Peano numbers, but in GHCi you can just run either of these functions:
> fromPeano (toPeano 5)
5
Or you can make a program and use print
to print out results:
main = print (toPeano 5829)
and use GHC to compile the program
$ ghc --make myProg.hs
$ ./myProg
Succ (Succ (Succ (...
Would something like this be what you're looking for?
toPeano 0 = Zero
toPeano n = Succ $ toPeano (n-1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With