Skip to content

Instantly share code, notes, and snippets.

@gclaramunt
Created July 11, 2014 21:59
Show Gist options
  • Save gclaramunt/1bd625c0553c90273a83 to your computer and use it in GitHub Desktop.
Save gclaramunt/1bd625c0553c90273a83 to your computer and use it in GitHub Desktop.
Middle of a list with the hare and tortoise method
-- | Main entry point to the application.
module Main where
-- | The main entry point.
main :: IO ()
main = do
putStrLn "Welcome to FP Haskell Center!"
putStrLn "Have a good day!"
putStrLn $ show $ middle [1]
putStrLn $ show $ middle [1,2]
putStrLn $ show $ middle [1,2,3]
putStrLn $ show $ middle [1,2,3,4]
putStrLn $ show $ middle [1,2,3,4,5]
middle :: [a] -> a
middle [x] = x
middle [x,y] = x
middle l = middle' l l
middle' :: [a] -> [a] -> a
middle' [] (x:l) = x
middle' [_] (x:l) = x
middle' (_:_:hare) (_:tortoise) = middle' hare tortoise
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment