I realise that using a functional paradigm everywhere does not always result in very readable code -- the code segment below is something I'm doing just as an exercise. What I'm trying to do is as follows :-
Given a list of strings(L) and a string(S) I need to find L[i]^S. If S exists in L, don't xor the strings together. L[i]^S would mean xoring the bytes in the same position with each other.
This is how I proceeded to solve the problem. I tried to break it down to its simplest form - i.e. xoring of two characters. If one of the inputs wouldn't be a character, I return a "".(I couldn't think of a better way to do this).
xor_char = lambda x, y: (chr(ord(x) ^ ord(y)) if x and y else "")
assert xor_char(None, "a") == ""
assert xor_char("a", " ") == "A"
Next, I try to write some code to xor the strings together.
from operator import add
xor_string = lambda string_one, string_two: reduce(add, (map(xor_char, string_one, string_two) if string_one != string_two else ""))
assert xor_string("asdf", "asdfg") == "\x00\x00\x00\x00"
assert xor_string("asdf", " ") == "ASDF"
Then, finally I try to perform this on a list of strings and a string.
xor_list_string = lambda l, s: map(xor_string, l, [s]*len(l))
print xor_list_string(a_list, a_string)
I get an error as follows on running the above line :-
Traceback (most recent call last):
File "2.py", line 26, in <module>
main()
File "2.py", line 23, in main
analyze(all_lines, all_lines[-1])
File "2.py", line 18, in analyze
print xor_list_string(a_list, a_string)
File "2.py", line 17, in <lambda>
xor_list_string = lambda l, s: map(xor_string, l, [s]*len(l))
File "2.py", line 11, in <lambda>
xor_string = lambda string_one, string_two: reduce(add, (map(xor_char, string_one, string_two) if string_one != string_two else ""))
TypeError: reduce() of empty sequence with no initial value
What am I doing wrong?
Is there anything wrong with how I'm trying to solve the problem using functional programming?
- Any obvious improvements you can think of?(the improvements would have to adhere to the functional paradigm too -- I'm doing this as a thought exercise, not in any project).