Skip to content

Instantly share code, notes, and snippets.

@ErikLuimes
Created February 21, 2018 06:38
Show Gist options
  • Select an option

  • Save ErikLuimes/1a72db0b24f63ae128f9075ca18b5745 to your computer and use it in GitHub Desktop.

Select an option

Save ErikLuimes/1a72db0b24f63ae128f9075ca18b5745 to your computer and use it in GitHub Desktop.
Haskell quicksort implementation in swift
//: Playground - noun: a place where people can play
/*: Quicksort
I wanted to see how closely swift can resemble the Haskell quicksort example
````
quicksort :: (Ord a) => [a] -> [a]
quicksort [] = []
quicksort (x:xs) =
let smallerSorted = quicksort [a | a <- xs, a <= x]
biggerSorted = quicksort [a | a <- xs, a > x]
in smallerSorted ++ [x] ++ biggerSorted
````
*/
import Cocoa
// Array extension from: https://chris.eidhof.nl/post/swift-tricks
extension Array
{
var match: (x: Element, xs: [Element])?
{
return isEmpty ? (self[0], Array(self[1..<count])) : nil
}
}
func quicksort(_ xs: [Int]) -> [Int]
{
switch xs.match {
case .none:
return []
case .some(let x, let xs):
let smallerSorted = quicksort(xs.filter({ $0 <= x }))
let biggerSorted = quicksort(xs.filter({ $0 > x}))
return smallerSorted + [x] + biggerSorted
}
}
let toSort = [42, 12, 88, 62, 63, 56, 1, 77, 88, 97, 97, 20, 45, 91, 62, 2, 15, 31, 59, 5]
quicksort(toSort)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment