Skip to content

Instantly share code, notes, and snippets.

@hiroshi-maybe
Created August 28, 2015 08:14
Show Gist options
  • Select an option

  • Save hiroshi-maybe/fc31a02d3d3e4658c929 to your computer and use it in GitHub Desktop.

Select an option

Save hiroshi-maybe/fc31a02d3d3e4658c929 to your computer and use it in GitHub Desktop.
example of protocol extension
//: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
/*
class (Eq a, Show a) => Num a where
(+) :: a -> a -> a
(-) :: a -> a -> a
(*) :: a -> a -> a
negate :: a -> a
abs :: a -> a
signum :: a -> a
fromInteger :: Integer -> a
fromInt :: Int -> a
*/
protocol Num: CustomStringConvertible, Equatable {
func +(left: Self, right: Self) -> Self
func -(left: Self, right: Self) -> Self
func *(left: Self, right: Self) -> Self
var isNegative: Bool { get }
var negate: Self { get }
var abs: Self { get }
static func fromInt(intValue: Int) -> Self
}
extension Num {
var negate: Self {
return isNegative ? self : Self.fromInt(-1) * self
}
var abs: Self {
return !isNegative ? self : Self.fromInt(-1) * self
}
}
/*
instance Num Int
*/
extension Int: Num {
var isNegative: Bool { return self < 0 }
static func fromInt(intValue: Int) -> Int {
return intValue
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment