Skip to content

Instantly share code, notes, and snippets.

@gja gja/basics-1.hs Secret
Last active Jan 4, 2016

Embed
What would you like to do?
Hydra Implementation in Haskell
let firstArray = 0:1:[2, 3]
-- [0, 1, 2, 3]
let infiniteOnes = 1:infiniteOnes
-- [1, 1, 1, 1, 1, ........................]
-- never stops, hit ctrl-C to get your interpreter back
sumOfElements [] = 0
sumOfElements (x:xs) = x + sumOfElements xs
[1] ++ [3] -- [1, 3]
null [] -- True
null [1] -- False
replicate 2 3 -- [3, 3]
chop [] = []
chop (1:xs) = xs
chop (n:xs) = (replicate (n - 1) (n - 1)) ++ xs
----------------------------------------------------
chop [1]
-- []
chop [4]
-- [3, 3, 3]
chop [3, 3, 3]
-- [2, 2, 3, 3]
chop [9,9,9,9,9,9,9,9,9]
-- [8,8,8,8,8,8,8,8,9,9,9,9,9,9,9,9]
countOfChops heads = length (repeatedlyChopTillDead heads)
--------------------------------------------------
countOfChops [1] -- 1
countOfChops [3] -- 5
countOfChops [9,9,9,9,9,9,9,9,9] -- 986409 (this takes a while)
willHerculesDie n heads = any (> n) (map length (repeatedlyChopTillDead heads))
----------------------------------------------------------------------------
willHerculesDie 37 [9,9,9,9,9,9,9,9,9] -- False
willHerculesDie 36 [9,9,9,9,9,9,9,9,9] -- True
-- To load this, save this as hydra.hs
-- then run ghci, and type :l hydra (colon ell hydra)
module Hydra where
firstArray = 0:1:[2, 3]
infiniteOnes = 1:infiniteOnes
chop [] = []
chop (1:xs) = xs
chop (n:xs) = (replicate (n - 1) (n - 1)) ++ xs
-- repeatedlyChop heads = heads:repeatedlyChop (chop heads)
-- takeWhileAlive (x:xs) = if null x then [] else x:(takeWhileAlive xs)
-- repeatedlyChopTillDead heads = takeWhileAlive (repeatedlyChop heads)
repeatedlyChopTillDead heads = takeWhile (not.null) (iterate chop heads)
countOfChops heads = length (repeatedlyChopTillDead heads)
willHerculesDie n heads = any (> n) (map length (repeatedlyChopTillDead heads))
repeatedlyChopTillDead heads = takeWhileAlive (repeatedlyChopTillDead heads)
----------------------------------------------------------------------------
repeatedlyChopTillDead [4]
-- [[4],[3,3,3],[2,2,3,3],[1,2,3,3],[2,3,3],[1,3,3],[3,3],[2,2,3],[1,2,3],[2,3],[1,3],[3],[2,2],[1,2],[2],[1]]
repeatedlyChop heads = heads:repeatedlyChop (chop heads)
----------------------------------------------------------
repeatedlyChop [3]
-- [[3],[2,2],[1,2],[2],[1], [], [], [] ...]
-- this is an infinite list
repeatedlyChop heads = iterate chop heads
repeatedlyChopTillDead heads = takeWhile (not.null) (iterate chop heads)
takeWhileAlive (x:xs) = if null x then [] else x:(takeWhileAlive xs)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.