Last active
December 25, 2015 00:39
-
-
Save ashleygwilliams/6889330 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-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). |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] |
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)
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.
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
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:expected output should be: