So, I have this problem where I have to call a recursive function inside another recursive function. The reason why I am opting for this is that I have to implement a while
loop in Elixir which calls a function inside of it recursively. An example of what I want to do in Python is the following:
def function(map, newList, origin):
mylist = map[origin]
while mylist:
nextVal = mylist.pop()
function(map, newList, origin)
newList.append(map, newList, origin)
Over here, we first get a value from map
, then loop over mylist
until it size becomes zero. Inside this loop, I extract the last element of the list and then pass that into the function as the updated origin
.
My implementation of this is the following:
defmodule MyFunction do
def function(map, newList, list, origin) do
if length(list) > 0 do
function(map, newList, origin)
else
newList
end
end
def function(map, newList, origin) do
list = map[origin]
origin = hd(list)
list = tl(list)
newList = function(map, newList, list, origin)
[origin | newList]
end
end
map
basically contains strings as keys and lists as its values, which contains multiple strings. An example of this is:
%{"HELLO" -> ["SKY"],
"SKY" -> ["WORLD"],
"KING" -> ["NEW"],
"WORLD" -> ["KING"]
}
origin
over here is a string such as HELLO
. This, however, only adds the first origin value to newList
. Does anyone know what I am doing wrong?
Any help will be appreciated. Been stuck on this for too long