Advertisement
softwarewisdom

Counting with natural numbers

Jan 10th, 2023
364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haskell 1.54 KB | Source Code | 0 0
  1. {-
  2. To execute this program, paste this source code into:
  3.  
  4. https://replit.com/languages/haskell
  5.  
  6. Counts the items in any finite list (which may be empty).
  7.  
  8. The return value of the 'count' function is a natural number (which, as this codes demonstrates, may be Zero, otherwise we cannot count the items of *any* finite list).
  9. -}
  10.  
  11. data Natural = Zero | SuccessorOf Natural
  12.    deriving Show
  13.  
  14. plus :: Natural -> Natural -> Natural
  15. plus Zero n = n
  16. plus (SuccessorOf m) n = SuccessorOf (m `plus` n)
  17.  
  18. data CharList = EmptyList | InhabitedListMadeOf Char CharList
  19.    deriving Show
  20.  
  21. count :: CharList -> Natural
  22. count EmptyList = Zero
  23. count (InhabitedListMadeOf head tail) = (SuccessorOf Zero) `plus` (count tail)
  24.  
  25. listOf1Item = InhabitedListMadeOf 'a' EmptyList
  26.  
  27. listOf2Items = InhabitedListMadeOf 'b' listOf1Item
  28.  
  29. listOf3Items = InhabitedListMadeOf 'c' listOf2Items
  30.  
  31. main = putStrLn $
  32.    (show EmptyList) ++ " => " ++ (show $ count EmptyList) ++ "."
  33.    ++ "\n\n" ++
  34.    (show listOf1Item) ++ " => " ++ (show $ count listOf1Item) ++ "."
  35.    ++ "\n\n" ++
  36.    (show listOf2Items) ++ " => " ++ (show $ count listOf2Items) ++ "."
  37.    ++ "\n\n" ++
  38.    (show listOf3Items) ++ " => " ++ (show $ count listOf3Items) ++ "."
  39.  
  40. {-
  41. Output:
  42.  
  43. EmptyList => Zero.
  44.  
  45. InhabitedListMadeOf 'a' EmptyList => SuccessorOf Zero.
  46.  
  47. InhabitedListMadeOf 'b' (InhabitedListMadeOf 'a' EmptyList) => SuccessorOf (SuccessorOf Zero).
  48.  
  49. InhabitedListMadeOf 'c' (InhabitedListMadeOf 'b' (InhabitedListMadeOf 'a' EmptyList)) => SuccessorOf (SuccessorOf (SuccessorOf Zero)).
  50. -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement