Haskell Peano Rooms

I am trying to write a function

toPeano :: Int -> Nat toPeano n = 

which turns Integer into its Peano number.

I have data:

 data Nat = Zero | Succ Nat deriving Show 

For example,

 toPeano 0 = Zero toPeano 1 = Succ Zero toPeano 2 = Succ (Succ Zero) 

etc.

I have no idea how to get him to print Peano numbers with an integer. I have never worked with Peano numbers, so any help with this would be greatly appreciated!

Thanks!

+7
source share
2 answers

Your question is not clear, so I will start with the conversion:

 toPeano 0 = Zero toPeano 1 = Succ Zero toPeano 2 = Succ (Succ Zero) 

This is pretty explicit. You can define Peano numbers with simple recursion and have this 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 Succ (toPeano (x-1)) - it just subtracts one from the whole and adds it to the Peano construct.

Now what about a different direction? Well, every time you see "Succ", you can simply add it:

 fromPeano Zero = 0 fromPeano (Succ x) = 1 + fromPeano x -- note this is inefficent but right now we don't care 

Print results

Now, the only part of what you said looked like a question:

I have no idea how to get him to print Peano numbers with an integer.

This has nothing to do with Peano numbers, but in GHCi you can simply run any of these functions:

 > fromPeano (toPeano 5) 5 

Or you can make a program and use print to print the results:

 main = print (toPeano 5829) 

and use ghc to compile the program

 $ ghc --make myProg.hs $ ./myProg Succ (Succ (Succ (... 
+7
source

Something like this will be what you are looking for?

 toPeano 0 = Zero toPeano n = Succ $ toPeano (n-1) 
+1
source

All Articles