Skip to content

Instantly share code, notes, and snippets.

@jiamo
Last active May 25, 2018 17:35
Show Gist options
  • Save jiamo/4a7556c7977beee05a6c1796b5947175 to your computer and use it in GitHub Desktop.
Save jiamo/4a7556c7977beee05a6c1796b5947175 to your computer and use it in GitHub Desktop.
high order function transform example 1
module Cartesian_product1 where
import Prelude hiding(product)
product1 [] = [[]]
product1 (xs:xss) =
h xs (product1 xss) where
h [] xss = []
h (x : xs) xss =
map (x:) xss ++ h xs xss
mapa :: (b -> a) -> [a] -> [b] -> [a]
mapa g z l = foldr f z l where
f x y = (g x) : y
product2 [] = [[]]
product2 (xs:xss) =
h xs (product2 xss) where
h [] xss = []
h (x:xs) xss =
mapa (x:) (h xs xss) xss
product3 [] = [[]]
product3 (xs:xss) =
h xs (product3 xss) where
h [] xss = []
h (x:xs) xss =
foldr f (h xs xss) xss where
f xs yss = (x:xs):yss
-- some as cartProdN8 in Cartesian_product2
product4 [] = [[]]
product4 (xs:xss) =
h xs (product4 xss) where
h xs yss = foldr g [] xs where
g x zss = foldr f zss yss where
f xs yss = (x:xs):yss
--- product4 have the same struct like foldr
product5 xss =
foldr h [[]] xss where
h xs yss = foldr g [] xs where
g x zss = foldr f zss yss where
f xs yss = (x:xs):yss
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment