Skip to content

Instantly share code, notes, and snippets.

@ashleygwilliams
Last active December 25, 2015 00:39
Show Gist options
  • Save ashleygwilliams/6889330 to your computer and use it in GitHub Desktop.
Save ashleygwilliams/6889330 to your computer and use it in GitHub Desktop.
-module(listmaker).
-export([add_to_head/2, add_to_tail/2, add_to_tail_recursive/2]).
-import(flatten, [flatten/1]).
%% add a non-list item to the beginning of a list
-spec(add_to_head(any(), list()) -> list()).
add_to_head(Item, List) -> [Item | List].
%% add a non-list item to the end of a list
-spec(add_to_tail(any(), list()) -> list()).
add_to_tail(Item, List) -> lists:reverse([ Item | lists:reverse(List) ]).
%% add a non-list item to the end of a list, recursively
-spec(add_to_tail_recursive(any(), list()) -> list()).
add_to_tail_recursive(Item, List) -> add_to_tail_recursive(Item, lists:reverse(List), poop).
%% helper to first revese the string received
add_to_tail_recursive(Item, [], poop) -> lists:reverse(Item);
%% then build the list with the item to add, backwards
add_to_tail_recursive(Item, [H|T], poop) -> add_to_tail_recursive( flatten([Item | [ H | [] ]]), T, poop).
Eshell V5.9.3.1 (abort with ^G)
1> c(listmaker).
{ok,listmaker}
2> listmaker:add_to_tail(8, [1,2,3]).
[1,2,3,8]
3>
2> listmaker:add_to_tail_recursive(5, [1,2,3,4]).
[1,2,3,4,5]
@tsantero
Copy link

tsantero commented Oct 8, 2013

to return a list without the constructor you should pass in a list as the Item and glue the two lists together with the ++ operator, such as:

-spec(add_to_tail(list(), list()) -> list()).
add_to_tail(Item, List) -> List ++ Item.

expected output should be:

1> c(listmaker).
{ok,listmaker}
2> MyList = [4,5,6].
[4,5,6]
3> listmaker:add_to_tail([8], MyList).
[4,5,6,8]

@ashleygwilliams
Copy link
Author

now with the recursive version i get this:

10> listmaker:add_to_tail_recursive(5, [1,2,3,4]).
** exception error: bad argument
     in function  hd/1
        called as hd([])
     in call from listmaker:add_to_tail_recursive/2 (listmaker.erl, line 10)

@ashleygwilliams
Copy link
Author

now i just get:

36> listmaker:add_to_tail_recursive(5, [1,2,3,4]).
[4,3,2,1,5]

WHERE TO REVERSE? arrararrr.
i know i need to reverse the string i'm getting but i don't know how/when/where.

@ashleygwilliams
Copy link
Author

ok so that poop atom is not the most elegant solution... but works for now?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment