Skip to content

Haskell snippet

Kamil Adam edited this page Sep 28, 2023 · 2 revisions

Factorial

Normal Haskell

factorial :: Integer -> Integer
factorial 0 = 1
factorial n = n * factorial (n-1)

main :: IO ()
main = do 
  n <- getInt
  print(factorial n)

Simply Haskell

factorialFix = \rec n -> if n <= 1 then 1 else n * rec (n-1)

factorial = \n -> fix factorialFix n

natFromStr = \ s -> read s
 
strFromNat = \ n -> show n

mainStrStr = \s -> natFromStr (factorial (strFromNat s))

main = do
  s <- getStr
  putStr (mainStrStr s)

PS

fix = ???

factorialFix = \rec n -> if n <= 1 then 1 else n * rec (n-1)

factorial = \n -> fix factorialFix n

natFromStr = \ s -> ???
 
strFromNat = \ n -> ?

mainStrStr = \s -> natFromStr (factorial (strFromNat s))

main = mainStrStr

FizzBuzz

fizz :: Int -> String
fizz n | n `mod` 15 == 0  = "FizzBuzz"
       | n `mod` 3  == 0  = "Fizz"
       | n `mod` 5  == 0  = "Buzz"
       | otherwise        = show n

main :: IO()
main = mapM_ putStrLn $ map fizz [1..100]

Fibonacci

Naive

fib 0 = 0
fib 1 = 1
fib n = fib (n-1) + fib (n-2)

Normal

fibs = map fst $ iterate (\(a,b) -> (b,a+b)) (0,1)
Clone this wiki locally