Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

# Permutations of a list:

- haskell:

  perms [] = [[]]
  perms xs = [ x:ps | x <- xs , ps <- perms ( xs\\[x] ) ]
- js: (using https://github.com/tc39/proposal-slice-notation for conciseness)

  const perms = xs => xs.length === 0
    ? [[]]
    : xs.flatMap((xi, i) => perms([...xs[0:i], ...xs[i+1:]).map(xsi => [xi, ...xsi])

# Cartesian product of 2 or n lists

- haskell:

  cart2 xs ys = [(x,y) | x <- xs, y <- ys]

  cartn :: [[a]] -> [[a]];
  cartn [] = [[]]
  cartn(xs:xss) = [x:ys | x <- xs, ys <- yss]
                        where yss = cartn xss
- js:

  const cart2 = (xs, ys) => xs.flatMap(x => ys.map(y => [x,y]));

  const cartn = (...args) => args.reduce((yss, xs) => yss.flatMap(ys => xs.map(x => [...ys, x])), [[]]);
  // or recursive
  const cartn = (xs, ...xss) => xss.length === 0
    ? xs
    : xs.flatMap(x => cartn(...xss).map(y => [x,y]))


Until now I didn't know about flatMap() and flat(). Thanks for this!




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

Search: