Skip to content

Instantly share code, notes, and snippets.

@yurrriq
Last active January 3, 2017 07:17
Show Gist options
  • Select an option

  • Save yurrriq/a66462e4c12603522052 to your computer and use it in GitHub Desktop.

Select an option

Save yurrriq/a66462e4c12603522052 to your computer and use it in GitHub Desktop.
zip two lists and foldl in one pass
;;; Notes:
;; - Doesn't check arity of `F'
;; - Like #'lists:zip/3, throws a function_clause exception
;; when given lists of unequal lengths
(defun zipfoldl
([f acc `(,ha . ,ta) `(,hb . ,tb)] (when (is_function f))
(zipfoldl f (funcall f ha hb acc) ta tb))
([f acc () ()] acc))
(include-lib "lfe/include/clj.lfe")
(defun hamming-distance (a b)
(flet ((f (x y sum) (cond-> sum (=/= x y) (+ 1))))
(zipfoldl #'f/3 0 a b)))
@yurrriq

yurrriq commented Aug 13, 2015

Copy link
Copy Markdown
Author

The Fun in #'lists:mapfoldl/3 behaves similarly:

Fun = fun((A, AccIn) -> {B, AccOut})

It might be good to have f take (x y acc)...

@yurrriq

yurrriq commented Aug 13, 2015

Copy link
Copy Markdown
Author

f could also be defined:

(flet ((f (z x y) (+ z (if (=:= x y) 0 1))))
  ...)

@yurrriq

yurrriq commented Aug 13, 2015

Copy link
Copy Markdown
Author

Basically analogous to a single-pass version of:

(defun zip-then-foldl (f z xs ys) (lists:foldl f z (lists:zip xs ys)))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment