I need a function which return the product of numbers in the string:
SomeFunc("1234") -> 1 * 2 * 3 * 4 = 24
Here is my code:
lists:foldr(fun(X, Y) ->开发者_运维知识库 X * Y end, 1, "1234").
But I get 6497400.
Why and how can I fix the code?
Your code is multiplying the ascii codes of the characters, i.e. 49*50*51*52. In order to get your desired result, use
lists:foldr(fun(X, Y) -> (X-$0)*Y end, 1, "1234")
where $0
is the ASCII code for the character '0'.
精彩评论