Skip to content

Instantly share code, notes, and snippets.

@alskipp
Last active January 6, 2024 07:23
Show Gist options
  • Save alskipp/f2bcf1cebfc88b41aca4 to your computer and use it in GitHub Desktop.
Save alskipp/f2bcf1cebfc88b41aca4 to your computer and use it in GitHub Desktop.
Filtering arrays of enums (Haskell / Swift 1.2 / Swift 2.0 comparison)
-- data structure for RGBA, RGB & CMYK colors
data Color = RGBA Float Float Float Float
| RGB Float Float Float
| CMYK Float Float Float Float
deriving (Eq, Ord, Show)
-- list of colors
colors = [ RGBA 0.1 0.1 0.5 0.2
, RGBA 1 1 0 0.9
, RGB 0.5 0.5 0
, RGB 1 1 1
, CMYK 1.0 1.0 0 0 ]
-- functions to filter color list by constructor
rgbas cols = [c| c@RGBA {} <- cols]
rgbs cols = [c| c@RGB {} <- cols]
cmyks cols = [c| c@CMYK {} <- cols]
-- filter color list
rgbaOnly = rgbas colors
rgbOnly = rgbs colors
cmykOnly = cmyks colors
// Swift 2.0
// enum for RGBA, RGB & CMYK colors
enum Color { // too much hassle to implement CustomStringConvertible Protocol
case RGBA(R:Double, G:Double, B:Double, A:Double)
case RGB(R:Double, G:Double, B:Double)
case CMYK(C:Double, M:Double, Y:Double, K:Double)
}
// functions to filter color by constructor (using `if case`)
extension Color {
var isRGBA : Bool {
if case .RGBA = self {
return true
}
return false
}
var isRGB : Bool {
if case .RGB = self {
return true
}
return false
}
var isCMYK : Bool {
if case .CMYK = self {
return true
}
return false
}
}
// array of colors
let colors = [
Color.RGBA(R: 0.5, G: 0.2, B: 0, A: 0.2),
Color.RGBA(R: 0, G: 0.9, B: 1, A: 0.9),
Color.RGB(R: 0.2, G: 1, B: 1),
Color.RGB(R: 0.1, G: 0.1, B: 0.9),
Color.CMYK(C: 1.0, M: 0, Y: 0, K: 0)]
// filter color list
colors.filter { $0.isRGBA }
colors.filter { $0.isRGB }
colors.filter { $0.isCMYK }
// An alternative is the following, which is truly terrible
var rgba:[Color] = []
for case let .RGBA(r, g, b, a) in colors {
rgba.append(.RGBA(R:r, G:g, B:b, A:a))
}
// Swift 1.2
// enum for RGBA, RGB & CMYK colors
enum Color { // can't be bothered to implement Printable Protocol
case RGBA(R:Double, G:Double, B:Double, A:Double)
case RGB(R:Double, G:Double, B:Double)
case CMYK(C:Double, M:Double, Y:Double, K:Double)
}
// functions to filter color by constructor (using `switch`)
extension Color {
var isRGBA : Bool {
switch self {
case .RGBA : return true
default : return false
}
}
var isRGB : Bool {
switch self {
case .RGB : return true
default : return false
}
}
var isCMYK : Bool {
switch self {
case .CMYK : return true
default : return false
}
}
}
// array of colors
let colors = [
Color.RGBA(R: 0.5, G: 0.2, B: 0, A: 0.2),
Color.RGBA(R: 0, G: 0.9, B: 1, A: 0.9),
Color.RGB(R: 0.2, G: 1, B: 1),
Color.RGB(R: 0.1, G: 0.1, B: 0.9),
Color.CMYK(C: 1.0, M: 0, Y: 0, K: 0)]
// filter color list
colors.filter { $0.isRGBA }
colors.filter { $0.isRGB }
colors.filter { $0.isCMYK }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment