• Stars
    star
    66
  • Rank 451,830 (Top 10 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 9 years ago
  • Updated over 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A set of protocols for Arithmetic, Statistics and Logical operations

Arithmosophi - Arithmosoϕ

Join the chat at https://gitter.im/phimage/Arithmosophi License Platform Language Issues Cocoapod Carthage compatible

Arithmosophi is a set of missing protocols that simplify arithmetic and statistics on generic objects or functions. As Equatable define the == operator , Addable will define the + operator.

protocol Addable {
    func + (lhs: Self, rhs: Self) -> Self
}
[1, 2, 3, 4].sum //  1 + 2 + 3 + 4
[0, 1, 2, 3, 4].average // 2
[13, 2.4, 3, 4].varianceSample
  • As you might guess Substractable define - operator, Multiplicatable define * operator, etc..., all defined in Arithmosophi.swift

Contents

Generic functions

Take a look at sumOf function

func sumOf<T where T:Addable, T:Initializable>(input : [T]) -> T {
    return reduce(input, T()) {$0 + $1}
}

Array of Int, Double and even String could be passed as argument to this function. Any Addable objects.

No need to implement a function for Double, one for Float, one more for Int, etc...

sumOf and productOf functions are available in Arithmosophi.swift

CollectionType

This framework contains some useful extensions on CollectionType

[1, 2, 3, 4].sum //  1 + 2 + 3 + 4
[1, 2, 3, 4].product //  1 * 2 * 3 * 4

["a","b","c","d"].sum // "abcd" same as joinWithSeparator("")
[["a","b"],["c"],["d"]].sum // ["a","b","c","d"] same as flatMap{$0}

Average

with MesosOros.swift

Computes arithmetic average/mean

[1, 2, 3, 4].average //  (1 + 2 + 3 + 4) / 4

A type is Averagable if it can be dividable by an Int and define an operator to do that

func /(lhs: Self, rhs: Int) -> Self

All arithmetic type conform to this protocol and you can get an average for a CollectionType

P.S. You can conform to this protocol and Addable to make a custom average.

Median

with MesosOros.swift

Get the median value from the array

  • Returns the average of the two middle values if there is an even number of elements in the CollectionType.
[1, 11, 19, 4, -7].median // 4
  • Returns the lower of the two middle values if there is an even number of elements in the CollectionType.
[1.0, 11, 19.5, 4, 12, -7].medianLow // 4
  • Returns the higher of the two middle values if there is an even number of elements in the CollectionType.
[1, 11, 19, 4, 12, -7].medianHigh // 11

Variance

with Sigma.swift

Computes variance.

[1.0, 11, 19.5, 4, 12, -7].varianceSample
[1.0, 11, 19.5, 4, 12, -7].variancePopulation

Standard deviation

with Sigma.swift

Computes standard deviation.

[1.0, 11, 19.5, 4, 12, -7].standardDeviationSample
[[1.0, 11, 19.5, 4, 12, -7].standardDeviationPopulation

Skewness

with Sigma.swift

Computes skewness.

[1.0, 11, 19.5, 4, 12, -7].skewness // or .moment.skewness

Kurtosis

with Sigma.swift

Computes kurtosis.

[1.0, 11, 19.5, 4, 12, -7].kurtosis // or .moment.kurtosis

Covariance

with Sigma.swift

Computes covariance with another CollectionType

[1, 2, 3.5, 3.7, 8, 12].covarianceSample([0.5, 1, 2.1, 3.4, 3.4, 4])
  • population covariance
[1, 2, 3.5, 3.7, 8, 12].covariancePopulation([0.5, 1, 2.1, 3.4, 3.4, 4])
[1, 2, 3.5, 3.7, 8, 12].pearson([0.5, 1, 2.1, 3.4, 3.4, 4])

Complex

with Complex.swift Complex is a struct of two ArithmeticType, the real and the imaginary component

var complex = Complex(real: 12, imaginary: 9)
complex = 12 + 9.i

You can apply operation on it (+, -, *, /, ++, --, -)

result = complex + 8 // Complex(real: 20, imaginary: 9)

Complex(real: 12, imaginary: 9) + Complex(real: 8, imaginary: 1)
 // Complex(real: 20, imaginary: 10)

Object attributes

The power of this simple arithmetic protocols are released when using operators

If we implement a box object containing a generic T value

class Box<T> {
	var value: T
}

we can define some operators on it, in a generic way, like we can do with Equatable or Comparable

func +=<T where T:Addable> (inout box: Box<T>, addend: T) {
    box.value = box.value + addend
}
func -=<T where T:Substractable> (inout box: Box<T>, addend: T) {
    box.value = box.value - addend
}

how to use this operator:

var myInt: Box<Int>(5)
myInt += 37

For a full example, see Prephirence file from Prephirences framework, or sample Box.swift

Optional trick

For optional attribute you can use Initializable or any protocol which define a way to get a value

class Box<T> {
	var value: T?
}
func +=<T where T:Addable, T:Initializable> (inout box: Box<T>, addend: T) {
    box.value = (box.value ?? T()) + addend
}

Logical operations

LogicalOperationsType is a missing protocol for Bool inspired from BitwiseOperationsType (or IntegerArithmeticType)

The purpose is the same, implement functions without knowing the base type

You can for instance implement your own Boolean enum and implement the protocol

enum Boolean: LogicalOperationsType {case True, False}
func && (left: Boolean, @autoclosure right:  () -> Boolean) -> Boolean {
    switch left {
    case .False: return .False
    case .True:  return right()
    }
}
...

then create only one operator on Box for Bool, Boolean and any LogicalOperationsType

func &&=<T:LogicalOperationsType> (inout box: Box<T>, @autoclosure right:  () -> TT) {
    box.value = box.value && right()
}

Take a look at a more complex enum Optional which implement also LogicalOperationsType

Geometry

with Arithmos(number) & Statheros(constant)

Arithmos and Statheros add respectively functions and mathematical constants for Double, Float and CGFloat, allowing to implement generic functions without taking care of type

func distance<T: Arithmos>(#x: T, y: T) -> T {
	return x.hypot(y)
}

func radiansFromDegrees<T where T: Multiplicable, Dividable, T: Arithmos, T: Statheros>(degrees: T) -> T {
	return degrees * T.PI / T(180.0)
}

Take a look at Geometry.swift for more examples

Setup

Using cocoapods

pod 'Arithmosophi'

Not interested in full framework ? install a subset with:

pod 'Arithmosophi/Core' # Arithmosophi.swift
pod 'Arithmosophi/Logical' # LogicalOperationsType.swift
pod 'Arithmosophi/Complex' # Complex.swift
pod 'Arithmosophi/MesosOros' # MesosOros.swift
pod 'Arithmosophi/Arithmos' # Arithmos.swift
pod 'Arithmosophi/Sigma' # Sigma.swift
pod 'Arithmosophi/Statheros' # Statheros.swift

pod 'Arithmosophi/Samples' # Samples/*.swift (not installed by default)

Add use_frameworks! to the end of the Podfile.

Make your own framework dependent

In podspec file

s.dependency 'Arithmosophi'

or define only wanted targets

s.dependency 'Arithmosophi/Core'
s.dependency 'Arithmosophi/Logical'

Using xcode

Drag files to your projects

More Repositories

1

Prephirences

Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, configurations and app-state. UserDefaults
Swift
568
star
2

Erik

Erik is an headless browser based on WebKit. An headless browser allow to run functional tests, to access and manipulate webpages using javascript.
Swift
564
star
3

CallbackURLKit

Implementation of x-callback-url (Inter app communication) in swift
Swift
323
star
4

CustomSegue

Custom segue for OSX Storyboards with slide and cross fade effects (NSViewControllerTransitionOptions)
Swift
124
star
5

morphi

Shapes for SwiftUI ♡☾
Swift
71
star
6

ApplicationGroupKit

Share informations betweens your applications and your extensions using group identifier
Swift
38
star
7

Alamofire-Prephirences

Remote preference and configuration for your application
Swift
22
star
8

MacModelDump

Dump apple website to get mac model identifier and image url
Swift
21
star
9

XcodeProjKit

Parse project file and write it to open step format.
Swift
14
star
10

CryptoPrephirences

Add some encryption to your sensitive preferences
Swift
11
star
11

Phiole

Allow to write or read from standards stream or files for script or CLI application
Swift
8
star
12

SLF4Swift

Simple Logging Facade for Swift serves as a simple facade for logging frameworks allowing the end user to plug in the desired logging framework at deployment time
Swift
8
star
13

Notarize

Command line utility to notarize apple application
Swift
8
star
14

ValueTransformerKit

ValueTransformer toolkit for swift
Swift
8
star
15

AlertController

An NSViewController to display an alert message to the user. This class replaces the NSAlert class.
Swift
8
star
16

MomXML

Create or parse CoreData managed object model XMLs
Swift
6
star
17

RandomDistributionKit

RandomKit extension to produce random numbers using different distribution
Swift
5
star
18

PhiLipsStack

(do not use) PhiLipsStack aims to create a CoreData stack from model to context and provide some functions on your managed object which use by default the default stack context but not only
Swift
5
star
19

Alamofire-YamlSwift

Add Yaml response serializer to Alamofire
Swift
4
star
20

plistconvert

Convert plist from different format: xml, json, binary, openStep
Shell
3
star
21

action-swift-cli-build

Build swift cli tool on macOS or ubuntu
3
star
22

FileZipKit

FileKit and ZipFoundation utility methods
Swift
3
star
23

NotarizeProcess

Utility object to launch `xcrun altool` to get notarization information
Swift
3
star
24

punic

Add third party project sources into your workspace instead of Carthage binary
Swift
3
star
25

sebulba

Swift command line to remove de-integrate reference to cocoa pods
Swift
2
star
26

Appify

Generate simple macOS `.app` from Swift Package `.executable`.
Swift
2
star
27

swift-cli-template

Shell
2
star
28

tanit

Command line application to manage Carthage binaries
Swift
1
star
29

NotarizationInfo

Decode info from apple notarization process
Swift
1
star
30

NotarizationAuditLog

Decode JSON audit log from notarization process
Swift
1
star
31

phimage

1
star
32

xprojup

Swift
1
star
33

cd2sql

Convert CoreData model into SQL
Swift
1
star