Re: natural numbers
Hamilton Richards <[email protected]> Thu, 3 Aug 2006 15:39:40 -0500
| Newsgroups | gmane.comp.lang.haskell.hugs.user |
|---|---|
| Message-ID | <p06230903c0f80e07ddd3@[192.168.1.103]> |
At 10:14 PM +0200 2006/8/3, [email protected] wrote: >Hello, > >thanks a lot for the expeditious replies to my trifling question. >Here is another one: > >Can you tell me why the following does not function? I mean the last >part for converting number into the new data type. If this is not a >quick fix, please ignore it. As an utter beginner, I cannot estimate >the significance of my questions. > > > >data Nat = Zero | Succ Nat > >natToInt Zero = 0 >natToInt (Succ n) = (natToInt n) + 1 > >number n = case n of > 0 -> Zero > _ -> Succ(number(n-1)) > > Most likely the problem you encountered looked something like Main> number 0 ERROR - Cannot find "show" function for: *** Expression : number 0 *** Of type : Nat The easy solution is to add deriving (Show) to the definition of Nat. Or, if you want to do it yourself, instance Show Nat where show Zero = "Zero" show (Succ n) = "(Succ " ++ show n ++ ")" Either way, you're providing a conversion from Nat to String, which is necessary if Nat values are ever to be displayed. Cheers, --Ham -- ------------------------------------------------------------------ Hamilton Richards, PhD Department of Computer Sciences Senior Lecturer (retired) The University of Texas at Austin [email protected] [email protected] http://www.cs.utexas.edu/users/ham/richards ------------------------------------------------------------------