Skip to content

Instantly share code, notes, and snippets.

@GeoffChurch
Last active December 15, 2020 14:40
Show Gist options
  • Save GeoffChurch/2bcf0c00327146b395838d1a544096ac to your computer and use it in GitHub Desktop.
Save GeoffChurch/2bcf0c00327146b395838d1a544096ac to your computer and use it in GitHub Desktop.
zip in terms of foldr
import Prelude hiding (zip)
-- `zip` accepts the first list and lazily returns a
-- function that accepts the second list and lazily
-- returns the list of pairs, so this implementation
-- is lazy in both arguments.
zip :: [a] -> [b] -> [(a, b)]
zip =
foldr
zipxs
-- Base case which discards any
-- remaining ys and returns []
(const [])
where
zipxs x zipxs' ys = case ys of
-- Base case which discards any
-- remaining xs and returns []
[] -> []
(y : ys) -> (x, y) : zipxs' ys
main :: IO ()
main = print $ take 4 $ zip [1, 3 ..] [2, 4 ..]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment