Fibonacci in Haskell

Published on 28 April 2022 (Updated: 02 February 2023)

Fibonacci in Haskell

Welcome to the Fibonacci in Haskell page! Here, you’ll find the source code for this program as well as a description of how the program works.

Current Solution

module Main where

import System.Environment
import Text.Read

fibonacci :: Int -> [Integer]
fibonacci = flip (take) fibs

fibs :: [Integer]
fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

headMaybe :: [a] -> Maybe a
headMaybe []     = Nothing
headMaybe (x:xs) = Just x

-- Takes a list of values and returns a list of strings in the format "ONE_BASED_INDEX: VALUE"
printWithIndex :: (Show a) => [a] -> [[Char]]
printWithIndex = zipWith (\i x -> (show i) ++ ": " ++ (show x)) [1..]

-- Prints out the first N numbers from the fibonacci sequence
-- where N equals to the first command line argument.
main :: IO ()
main = do
  args <- getArgs
  let n = headMaybe args
  case n >>= readMaybe of
    Nothing -> putStrLn "Usage: please input the count of fibonacci numbers to output"
    Just n  -> mapM_ (putStrLn) $ (printWithIndex . fibonacci) n

Fibonacci in Haskell was written by:

If you see anything you’d like to change or update, please consider contributing.

Note: The solution shown above is the current solution in the Sample Programs repository as of Apr 07 2019 00:40:32. The solution was first committed on Oct 15 2018 18:50:33. As a result, documentation below may be outdated.

How to Implement the Solution

No ‘How to Implement the Solution’ section available. Please consider contributing.

How to Run the Solution

No ‘How to Run the Solution’ section available. Please consider contributing.