Recently, I made a small algorithm to extract function arguments from a piece of code and save only the most external functions. I found that this algorithm is very easy to develop for real. However, I am really interested in functional programming, and I was wondering how you would do the same in a functional way.
It would be very helpful if you could show me how such an algorithm can work, so I could better understand how functional programming works. I would also like to know what your thought process is when developing an algorithm.
I made an imperative version in Python, but your answer does not have to be in python; haskell or any other language will do the same.
Here is what it does (taking the string as input and the return string):
"foo(a.d, b.e.fi()).go(sd, ds())" -- returns --> "foo().go()"
"foo(a, b).bar().fuu" -- returns --> "foo().bar().fuu"
"foo.bar" -- returns --> "foo.bar"
And here is my imperative code:
def get_rid_of_arguments(text):
i, start, end = 0, 0, 0
result = ""
for j, c in enumerate(text):
if c == '(':
if i == 0:
start = j
result += text[end:start]
i += 1
elif c == ')':
i -= 1
if i == 0:
end = j + 1
result += '()'
return result + text[end:]
source
share