Skip to content

Instantly share code, notes, and snippets.

@eungju
Created September 21, 2011 04:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eungju/1231267 to your computer and use it in GitHub Desktop.
Save eungju/1231267 to your computer and use it in GitHub Desktop.
Look-and-say sequence
(defn look-and-say [input]
((fn [input acc]
(if (empty? input)
(reverse acc)
(let [[x & xs] input [i n & as] acc]
(if (= x i)
(recur xs (list* x (inc n) as))
(recur xs (list* x 1 acc))))))
(rest input) [(first input) 1]))
(println (look-and-say [1]))
(println (look-and-say [1 1]))
(println (look-and-say [2 1]))
(println (look-and-say [1 2 1 1]))
(println (look-and-say [1 1 1 2 2 1]))
-module(look_and_say).
-export([look_and_say/1, main/0]).
look_and_say(L) ->
look_and_say(L, []).
look_and_say([], Acc) ->
lists:reverse(Acc);
look_and_say([X|XS], []) ->
look_and_say(XS, [X,1]);
look_and_say([X|XS], [X,N|AS]) ->
look_and_say(XS, [X,N + 1|AS]);
look_and_say([X|XS], Acc) ->
look_and_say(XS, [X,1|Acc]).
main() ->
io:format("~p~n", [look_and_say([])]),
io:format("~p~n", [look_and_say([1])]),
io:format("~p~n", [look_and_say([1,1])]),
io:format("~p~n", [look_and_say([2,1])]),
io:format("~p~n", [look_and_say([1,2,1,1])]),
io:format("~p~n", [look_and_say([1,1,1,2,2,1])]).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment