Fork me on GitHub

look and say sequence 2

This time I implement the look and say sequence in haskell, a functional language. This is clearly different from the pyton implementation, most notably by the fact that there is already a function called span that takes care of the tricky part of determining how many identical numbers that exists in a row. Span returns a list that then can be used calculate the length of the number of identical numbers, much like a chain of functions. So the main function, las, consists of three lines, the first one is the optional type declaration, second is the recursive base case and the final one is the recursive call. The second intresting function is the unfoldr function that takes one function with a Maybe claus that is used for the recursive case. The type specification has to be determined by the argument, in this case [1] ([Int]). This is an elegant way of doing a recursion in a one line sentence.

The implementation of the look and see sequence in haskell:

import Data.List

las :: [Int] -> [Int]
las [] = []
las (x:xs) = [length $ fst $ span (==x) (x:xs)] ++ [x] ++ las (snd(span (==x) xs))

main = do
 putStr "enter max length: "
 seqs <- getLine
 putStr "enter start value: "
 st <- getLine
 let se=read seqs
     seed=read st
 let st=unfoldr (\x -> if length (last [x])>se then Nothing else Just (las x,las x)) [seed]
 putStrLn (show st)

Comments !