Sort 76 Discussions, By:
Please Login in order to post a comment
f arr = sum (filter odd arr)
-- OR --
f = sum . filter odd
it is strange thar -3 % 2 ==-1 in scala
so my first code :"arr.filter(_%2==1).sum" is faild when negative number in the input .
fix it by _%2!=0
Same in Erlang, I used
case abs(N rem 2) of
1 -> true;
0 -> false
In Erlang you also can do it without 'abs':
E rem 2 /= 0 -> Acc + E;
true -> Acc
end, 0, List)
There's nothing strange (and this goes for every language), as the definition of Euclidean division requires remainder to be within [0, |b|) range. For the remainder to be positive, use r = ((a % b) + b) % b formula.
r = ((a % b) + b) % b
This is very nice explanation on the reminder behavior. Thanks for sharing.
(fn [lst] (reduce + (filter odd? lst)))
def f(arr:List[Int]) = arr filter(_ % 2 != 0) reduceLeft(_ + _)
Nice way to dodge a bullet with negative numbers!
I fell for that trap
me too :(
arr.filter(_ % 2 != 0).sum
any reason for reduceLeft over sum?
what does reduce left do or foldleft ?
(defun sum-odd (lst)
(apply '+ (remove-if-not #'oddp lst)))