A set of protocols for Arithmetic, Statistics and Logical operations

Related tags

Math Arithmosophi
Overview

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

You might also like...
A Swift probability and statistics library

Probably Probably is a set of Swift structures for computing the probability and cumulative distributions of different probablistic functions. Right n

Premier League and LaLiga live statistics
Premier League and LaLiga live statistics

FootballLiveData Premier League and LaLiga live standings tables and players sta

LeetStats - iOS iPadOS application to get your Leetcode statistics using their public API while extensively making use of Charts and visualisation to depict data 🇬🇧 UK COVID-19 Statistics app built using SwiftUI
🇬🇧 UK COVID-19 Statistics app built using SwiftUI

🇬🇧 UK COVID-19 Statistics This app was created with the intention of publishing to the AppStore. The primary purpose of this app is to share informa

OpenFocusTimer - Pomodoro timer with categories, reflection, history & statistics

OpenFocusTimer Pomodoro timer with categories, reflection, history & statistics.

A beautiful set of predefined colors and a set of color methods to make your iOS/OSX development life easier.
A beautiful set of predefined colors and a set of color methods to make your iOS/OSX development life easier.

Installation Drag the included Colours.h and Colours.m files into your project. They are located in the top-level directory. You can see a demo of how

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

Prephirences - Preϕrences Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, co

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

Prephirences - Preϕrences Prephirences is a Swift library that provides useful protocols and convenience methods to manage application preferences, co

MailCore 2 provide a simple and asynchronous API to work with e-mail protocols IMAP, POP and SMTP.

MailCore 2: Introduction MailCore 2 provides a simple and asynchronous Objective-C API to work with the e-mail protocols IMAP, POP and SMTP. The API h

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.
FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias.

FluxCapacitor makes implementing Flux design pattern easily with protocols and typealias. Storable protocol Actionable protocol Dispatch

The core LibP2P Interfaces / Protocols and Abstractions backing the swift-libp2p project
The core LibP2P Interfaces / Protocols and Abstractions backing the swift-libp2p project

LibP2PCore The core LibP2P Interfaces / Protocols and Abstractions backing the swift-libp2p project Table of Contents Overview Install Usage Example A

Xcode Plugin helps you find missing methods in your class header, protocols, and super class, also makes fast inserting.

FastStub-Xcode Life is short, why waste it on meaningless typing? What is it? A code generating feature borrowed from Android Studio. FastStub automat

Easy XML parsing using Codable protocols in Swift

XMLCoder Encoder & Decoder for XML using Swift's Codable protocols. This package is a fork of the original ShawnMoore/XMLParsing with more features an

A wrapper around UICollectionViewController enabling a declarative API around it's delegate methods using protocols.

Thunder Collection Thunder Collection is a useful framework which enables quick and easy creation of collection views in iOS using a declarative appro

Protocols for your every day iOS needs
Protocols for your every day iOS needs

Standard Template Protocols Essential protocols for your every day iOS needs Example UIGestureRecognizerProtocols About Swift 2.0 opens a world of opp

Kraken - Simple Dependency Injection container for Swift. Use protocols to resolve dependencies with easy-to-use syntax!
Kraken - Simple Dependency Injection container for Swift. Use protocols to resolve dependencies with easy-to-use syntax!

Kraken Photo courtesy of www.krakenstudios.blogspot.com Introduction Kraken is a simple Dependency Injection Container. It's aimed to be as simple as

FreeOTP is a two-factor authentication application for systems utilizing one-time password protocols

FreeOTP FreeOTP is a two-factor authentication application for systems utilizing one-time password protocols. Tokens can be added easily by scanning a

Swift package containing collection protocols.
Swift package containing collection protocols.

swift-collection-protocols A package containing collection protocols, for the Swift programming language. Overview No overview available. Availability

Comments
  • Kellyroach/add playground

    Kellyroach/add playground

    This pull request

    • Fixes Xcode 9.4.1 compiler warnings and build errors in Arithmosophi
    • Adds Arithmosophi.playground, a Swift playground.

    Compiler issues are fixed:

    • ArithmosophiOSX doesn't build. 6 yellow warning, 4 red build errors.
    • Update to recommended settings
    • warning: initializer for struct 'CGPoint' must use "self.init(...)" ...
    • Unneeded Break in Switch Violation: Avoid using unneeded break statements.
    • Expected named member of numeric literal
    • Cannot convert value of type 'Int' to expected argument type 'Double'

    Arithmosophi.playground: Adds some interactive fun to the the repo. The Swift playground demos Arithmosophi functionality, is a nice test bed, and may inspire the viewer to invent and test additional examples.

    opened by kellyroach 1
  • Swift 5.3 and SwiftPM

    Swift 5.3 and SwiftPM

    This is a "dressing" update to allow the library to be used with Xcode 12 (IE Swift 5) as well as Swift Package Manager. This has not been tested explicitly for Cocoapod usage.

    opened by BrettThePark 0
  • Add a Gitter chat badge to README.md

    Add a Gitter chat badge to README.md

    phimage/Arithmosophi now has a Chat Room on Gitter

    @phimage has just created a chat room. You can visit it here: https://gitter.im/phimage/Arithmosophi.

    This pull-request adds this badge to your README.md:

    Gitter

    If my aim is a little off, please let me know.

    Happy chatting.

    PS: Click here if you would prefer not to receive automatic pull-requests from Gitter in future.

    opened by gitter-badger 0
Releases(4.0.0)
Owner
Eric Marchand
🧙🍺🥊🥋🏓
Eric Marchand
VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions

Purpose VectorMath is a Swift library for Mac and iOS that implements common 2D and 3D vector and matrix functions, useful for games or vector-based g

Nick Lockwood 341 Dec 31, 2022
Overload +-*/ operator for Swift, make it easier to use (and not so strict)

Easy-Cal-Swift Overview This file is an overloading of +-*/ operator for Swift, to make it easier to use (and not so strict) It can make your life wit

Wei Wang 272 Jun 29, 2022
Numpy-like library in swift. (Multi-dimensional Array, ndarray, matrix and vector library)

Matft Matft is Numpy-like library in Swift. Function name and usage is similar to Numpy. Matft Feature & Usage Declaration MfArray MfType Subscription

null 80 Dec 21, 2022
SwiftMath is a Swift framework providing some useful math constructs and functions

SwiftMath is a Swift framework providing some useful math constructs and functions, like complex numbers, vectors, matrices, quaternions, and polynomials.

Matteo Battaglio 175 Dec 2, 2022
Beautiful math equation rendering on iOS and MacOS

iosMath iosMath is a library for displaying beautifully rendered math equations in iOS and MacOS applications. It typesets formulae written using the

Kostub Deshmukh 1.3k Dec 21, 2022
Metron is a comprehensive collection of geometric functions and types that extend the 2D geometric primitives

Metron Geometry, simplified. Metron is a comprehensive collection of geometric functions and types that extend the 2D geometric primitives provided by

Toine Heuvelmans 1k Dec 5, 2022
🔥 🔥 🔥Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

?? ?? ??Support for ORM operation,Customize the PQL syntax for quick queries,Support dynamic query,Secure thread protection mechanism,Support native operation,Support for XML configuration operations,Support compression, backup, porting MySQL, SQL Server operation,Support transaction operations.

null 60 Dec 12, 2022
Arbitrary-precision arithmetic in pure Swift

Overview API Documentation License Requirements and Integration Implementation Notes Full-width multiplication and division primitives Why is there no

null 707 Dec 19, 2022
🎯 PredicateKit allows Swift developers to write expressive and type-safe predicates for CoreData using key-paths, comparisons and logical operators, literal values, and functions.

?? PredicateKit PredicateKit is an alternative to NSPredicate allowing you to write expressive and type-safe predicates for CoreData using key-paths,

Faiçal Tchirou 352 Jan 3, 2023
Remember there's no such thing as a small act of kindness. Every act creates a ripple with no logical end.

Ripple is a small convenience to create ripples in your app. With just a line of code, you can do beautiful things. Code There are two types of ripple

Ramon Gilabert 87 May 15, 2022