3 ms·
One cann do this in Python, or any other language for that matter: def quicksort ( xs ): if len(list) == 0: return [] else: less = [x for x in
by Blikkentrekker 6y ago
One cann do this in Python, or any other language for that matter:
def quicksort ( xs ):
if len(list) == 0:
return []
else:
less = [x for x in xs[1:] if x <= xs[0]]
more = [x for x in xs[1:] if x > xs[0]]
return less + [xs[0]] + more
Not the most efficient implementation in either.
- wheybags 6y agoAnd IMO, that python version is one million % more readable. In particular, because you defined more and less before using them, vs after in the Haskell example. I don't know if there's a way that could be achieved in Haskell too though. Edit: you forgot the recursive calls though.
- harporoeder 6y agoHaskell has a `let ... in` syntax. Quoting from (1): quicksort1 :: (Ord a) => [a] -> [a] quicksort1 [] = [] quicksort1 (x:xs) = let smallerSorted = quicksort1 [a | a <- xs, a <= x] biggerSorted = quicksort1 [a | a <- xs, a > x] in smallerSorted ++ [x] ++ biggerSorted 1: http://learnyouahaskell.com/recursion http://learnyouahaskell.com/recursion
- FridgeSeal 6y agoI used to think so as well, until I realised at some point that defining things like this means you focus on the actual "business logic" up front, but the applicable definitions are never far (visually, spatially and logically). In my opinion it lets you get to grips on the overall logic before hassling you with certain specifics.
- adsharma 6y agoThe term "business logic" itself tends to be somewhat controversial: https://adsharma.github.io/flattools-programs/ https://adsharma.github.io/flattools-programs/
- 414owen 6y ago@wheybags I recommend achieving defined-before-use quicksort by throwing in some unnecessary Haskell syntax extensions: qs :: Ord a => [a] -> [a] qs = \case [] -> [] (x : (partition (< x) -> (qs -> as, qs -> bs))) -> as <> [x] <> bs
- n4r9 6y agoTrue, although you forgot the recursion. The Haskell filter expression is much nicer as well. You could perhaps be terser by using ternary conditionals: def quicksort ( xs ): return [] if len(list) == 0 else quicksort([x for x in xs[1:] if x <= xs[0]]) + xs[0] + quicksort([x for x in xs[1:] if x > xs[0]])