1
0

Add remaining haskell book exercises

This commit is contained in:
2025-12-11 10:28:11 +01:00
parent 3624c712d7
commit 98329e0a3d
221 changed files with 8033 additions and 2 deletions

16
Haskell-book/13/Cipher.hs Normal file
View File

@@ -0,0 +1,16 @@
module Cipher where
import Data.Char
import Data.List
vigenere :: String -> String
vigenere = f (cycle [0, 11, 11, 24])
where f _ [] = []
f ys (' ':xs) = ' ' : (f ys xs)
f (y:ys) (x:xs) = (decode (x, y)) : (f ys xs)
where decode (x, y) = chr ((mod ((ord x) - 65 + y) 26) + 65)
main :: IO ()
main = do
i <- getLine
putStrLn $ vigenere i

View File

@@ -0,0 +1,20 @@
module Palindrome where
import Control.Monad
import Data.Char
import System.Exit
format :: String -> String
format s = filter (\x -> x >= 'a' && x <= 'z') (map toLower s)
palindrome :: IO ()
palindrome = forever $ do
line1 <- getLine
case ((format line1) == (format $ reverse line1)) of
True -> putStrLn "It's a palindrome!"
False -> do
putStrLn "Nope!"
exitSuccess
main :: IO ()
main = palindrome

34
Haskell-book/13/Person.hs Normal file
View File

@@ -0,0 +1,34 @@
module Person where
type Name = String
type Age = Integer
data Person = Person Name Age deriving Show
data PersonInvalid = NameEmpty
| AgeTooLow
| PersonInvalidUnknown String
deriving (Eq, Show)
mkPerson :: Name -> Age -> Either PersonInvalid Person
mkPerson name age
| name /= "" && age > 0 = Right $ Person name age
| name == "" = Left NameEmpty
| not (age > 0) = Left AgeTooLow
| otherwise =
Left $ PersonInvalidUnknown $
"Name was: " ++ show name ++ " Age was: " ++ show age
showPerson :: Either PersonInvalid Person -> String
showPerson (Left NameEmpty) = "Name is empty"
showPerson (Left AgeTooLow) = "Age is too low"
showPerson (Left (PersonInvalidUnknown e)) = e
showPerson (Right p) = "Yay! Successfully got a person: " ++ (show p)
gimmePerson :: IO ()
gimmePerson = do
putStr "Enter your name: "
name <- getLine
putStr "Enter your age: "
age <- getLine
putStrLn $ showPerson $ mkPerson name (read age)