summaryrefslogtreecommitdiff
path: root/Haskell-book/09/src/Zipping.purs
blob: 32fe6dad5b1df0cec310c44bd112a0adae27e5ec (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module Zipping where

import Data.Array (head, tail, (:))
import Data.Maybe (Maybe(..))
import Data.Tuple (Tuple(..))

-- 1
zip :: forall a b. Array a -> Array b -> Array (Tuple a b)
zip a b = f (head a) (head b) (tail a) (tail b)
  where f Nothing _ _ _ = []
        f _ Nothing _ _ = []
        f _ _ Nothing _ = []
        f _ _ _ Nothing = []
        f (Just x) (Just y) (Just xs) (Just ys) = (Tuple x y) : (f (head xs) (head ys) (tail xs) (tail ys))

-- 2
zipWith :: forall a b c. (a -> b -> c) -> Array a -> Array b -> Array c
zipWith f a b = f' (head a) (head b) (tail a) (tail b)
  where f' Nothing _ _ _ = []
        f' _ Nothing _ _ = []
        f' _ _ Nothing _ = []
        f' _ _ _ Nothing = []
        f' (Just x) (Just y) (Just xs) (Just ys) = (f x y) : (f' (head xs) (head ys) (tail xs) (tail ys))

-- 3
zip' :: forall a b. Array a -> Array b -> Array (Tuple a b)
zip' = zipWith (\a b -> Tuple a b)