In today’s Programming Praxis exercise, our task is to generate the Look and Say sequence (1, 11, 21, 1211, etc.). Let’s get started, shall we?
A quick import:
The algorithm is pretty straightforward: convert the number to a string, replace each sequence of identical digits with the length followed by the digit and convert the result back to an integer. Repeat indefinitely.
lookAndSay :: Integer -> [Integer] lookAndSay = iterate (read . f . group . show) where f = (>>= \x -> show (length x) ++ take 1 x)
A test to see if everything is working properly:
main :: IO () main = print $ take 10 (lookAndSay 1) == [1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211, 31131211131221, 13211311123113112211]
Yup. Unfortunately there doesn’t appear to be a Haskell Package that does run-length encoding, or I might have been able to do it in one line.