Back to front pageView on Hacker News (opens in a new tab)Ask HN: What is the most beautiful piece of code you've ever read?476 pointsby seisvelas (on Hacker News)7 years agoPreferably an elegant snippet rather than an entire (well engineered) codebase.Comments (380) 116 threadsShow all commentsShowing thread 32 of 116[-]112358132134557 years ago1 reply## 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]))numlock867 years ago#Until now I didn't know about flatMap() and flat(). Thanks for this!
Ask HN: What is the most beautiful piece of code you've ever read?476 pointsby seisvelas (on Hacker News)7 years ago
112358132134557 years ago1 reply## 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]))
Comments (380) 116 threads
Show all comments
Showing thread 32 of 116
- haskell:
- js: (using https://github.com/tc39/proposal-slice-notation for conciseness) # Cartesian product of 2 or n lists- haskell:
- js: