In a python discusion, I saw a function to convert IP string into an integer in functional progamming way. Here is the Link .
The function is implemented in a single line.
def ipnumber(ip):
return reduce(lambda sum, chunk: sum <<8 | chunk, map(int, ip.split(".")))
However, I have few ideas of funcional programming. Could anybody explain the function in detail? I’ve some knowledge of “map” and “reduce”. But I don’t konw what “|” and “chunk” mean here.
Thanks.
sumandchunkare arguments to thelambdafunction passed toreduce.|is the binary or operator.The thing works like this:
ip.split(".")returns a list of strings, each corresponding to a piece of the dotted string ("192.168.0.1"=>["192", "168", "0", "1"];mapapplies its first operand to each element of its second operand (["192", "168", "0", "1"]=>[192, 168, 0, 1]);reducetakes the first two arguments from the list and applies thelambdato them; then it does this again with the result of the lambda and the next element of the list; and so on.the
labmdafunction (an anonymous function defined on the spot) does this: takes the first argument, shifts it by eight bits and ORs to it the new chunk; thus, what happens is that the result is computed like:which is exactly what the “dotted form” represents (it’s just a shorthand to indicate a 32 bit unsigned integer, which is what an IP is in IPv4 – you could say it’s a bit like expressing it in base 256)