Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
From while to fold (in F#) (richardminerich.com)
20 points by Rickasaurus on May 12, 2010 | hide | past | favorite | 2 comments


I 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))


So, 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: