Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- {-
- To execute this program, paste this source code into:
- https://replit.com/languages/haskell
- Counts the items in any finite list (which may be empty).
- 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).
- -}
- data Natural = Zero | SuccessorOf Natural
- deriving Show
- plus :: Natural -> Natural -> Natural
- plus Zero n = n
- plus (SuccessorOf m) n = SuccessorOf (m `plus` n)
- data CharList = EmptyList | InhabitedListMadeOf Char CharList
- deriving Show
- count :: CharList -> Natural
- count EmptyList = Zero
- count (InhabitedListMadeOf head tail) = (SuccessorOf Zero) `plus` (count tail)
- listOf1Item = InhabitedListMadeOf 'a' EmptyList
- listOf2Items = InhabitedListMadeOf 'b' listOf1Item
- listOf3Items = InhabitedListMadeOf 'c' listOf2Items
- main = putStrLn $
- (show EmptyList) ++ " => " ++ (show $ count EmptyList) ++ "."
- ++ "\n\n" ++
- (show listOf1Item) ++ " => " ++ (show $ count listOf1Item) ++ "."
- ++ "\n\n" ++
- (show listOf2Items) ++ " => " ++ (show $ count listOf2Items) ++ "."
- ++ "\n\n" ++
- (show listOf3Items) ++ " => " ++ (show $ count listOf3Items) ++ "."
- {-
- Output:
- EmptyList => Zero.
- InhabitedListMadeOf 'a' EmptyList => SuccessorOf Zero.
- InhabitedListMadeOf 'b' (InhabitedListMadeOf 'a' EmptyList) => SuccessorOf (SuccessorOf Zero).
- InhabitedListMadeOf 'c' (InhabitedListMadeOf 'b' (InhabitedListMadeOf 'a' EmptyList)) => SuccessorOf (SuccessorOf (SuccessorOf Zero)).
- -}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement