Skip to content

Instantly share code, notes, and snippets.

@ukitaka
Created February 6, 2018 08:46
Show Gist options
  • Save ukitaka/a995c8821ad5a831f675c8954ff1b713 to your computer and use it in GitHub Desktop.
Save ukitaka/a995c8821ad5a831f675c8954ff1b713 to your computer and use it in GitHub Desktop.
haskell-like-func-def.swift
protocol MyComparable {
static func < (lhs: Self, rhs: Self) -> Bool
static func >= (lhs: Self, rhs: Self) -> Bool
}
extension MyComparable {
static func < (lhs: Self, rhs: Self) -> Bool {
return !(rhs >= lhs)
}
static func >= (lhs: Self, rhs: Self) -> Bool {
return !(lhs < rhs)
}
}
struct MyInt1: MyComparable {
let n: Int
static func < (lhs: MyInt1, rhs: MyInt1) -> Bool {
return lhs.n < rhs.n
}
}
struct MyInt2: MyComparable {
let n: Int
static func >= (lhs: MyInt2, rhs: MyInt2) -> Bool {
return lhs.n >= rhs.n
}
}
MyInt1(n: 1) < MyInt1(n: 2) // true
MyInt1(n: 1) >= MyInt1(n: 2) // zsh: illegal hardware instruction swift comp.swift
MyInt2(n: 1) < MyInt2(n: 2)
MyInt2(n: 1) >= MyInt2(n: 2)
protocol MyInteger {
var isOdd: Bool { get }
var isEven: Bool { get }
}
extension MyInteger {
var isOdd: Bool {
return !isEven
}
var isEven: Bool {
return !isOdd
}
}
struct MyInteger1: MyInteger {
let n: Int
var isOdd: Bool {
return n % 2 == 1
}
}
struct MyInteger2: MyInteger {
let n: Int
var isEven: Bool {
return n % 2 == 0
}
}
// works well
MyInteger1(n: 1).isOdd
MyInteger1(n: 1).isEven
MyInteger2(n: 1).isOdd
MyInteger2(n: 1).isEven
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment