3 ms·
From while to fold (in F#)
- Xurinos 16y agoI just had to take a shot at it... (defun counter (numbers) (reverse (reduce #'(lambda (acc element) (cond ((null acc) (list element 1)) ((= (first acc) element) (cons element (cons (1+ (second acc)) (cddr acc)))) (t (cons element (cons 1 acc))))) numbers :initial-value nil))) (counter '(4 4 5 5 5 3 3))
- Amnon 16y agoSo, in essence, the post shows that you can always transform a for loop into a fold call (you can emulate the loop's mutable variables with function arguments). But I don't think the result is better in any sense than the original, imperative, style.