• Stars
    star
    409
  • Rank 105,709 (Top 3 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 10 years ago
  • Updated over 6 years ago

Reviews

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

Repository Details

Swift µframework of simple functional programming tools

Prelude

This is a Swift µframework providing a number of simple functions that I use in many of my other frameworks. Rather than continue to reimplement them for each consumer, I am gathering them here together.

Notably, this framework does not provide any new types, or any functions which operate on custom types; those presumably belong in µframeworks of their own.

Table of Contents

Gallery

Prelude’s functions are infinitely useful. Here’s a gallery of just a few of the things you can do with them.

id

Passing id as the argument to the flattenMap method of a Stream of Streams will flatten it out into a stream of all the nested elements:

func flatten<T>(stream: Stream<Stream<T>>) -> Stream<T> {
	return stream.flattenMap(id)
}

const

Passing the result of const to an Either is convenient for transforming it into an Optional<T>:

let result: Either<NSError, String> = 
if let string = result.either(const(nil), id) {
	println("ohai \($0)")
}

>>> and <<<

The left-to-right and right-to-left composition operators (>>> and <<< respectively) chain operations together:

let repl: File -> String = readLine >>> parseString >>> evaluateAST >>> toString
while true {
	println(repl(standardInput))
}

fix

You can use fix to make an anonymous function which calls itself recursively:

let factorial = fix { recur in
	{ n in n > 0 ? n * recur(n - 1) : 1 }
}

|> and <|

The forward and backward application operators (|> and <| respectively) apply the function on the side they’re pointing at to the value on the other side.

This can sometimes make code more readable. This is particularly the case for the forward application operator. x |> f is equivalent to f(x), but it reads in the direction that the data flows. The benefit is more obvious with longer function names:

100 |> toString |> count // => 3
// this is equivalent to
countElements(toString(100))

Backward application reads in the wrong direction for this—f <| x isn’t really any improvement on f(x). Unlike forward application, however, <| can apply binary and ternary functions to their first operands. This enables you to make something like Haskell’s operator sections:

let successor: Int -> Int = (+) <| 1
successor(3) // => 4
map([1, 2, 3], (*) <| 2) // => [2, 4, 6]

You can also combine |> and <| with flip to pass data through chains of higher-order functions like sorted, map, and reduce:

let result =
	[66, 78, 1, 95, 76]
|>	(flip(sorted) <| (<)) // sort in ascending order
|>	(flip(map) <| toString) // make them into strings
|>	String.join(", ") // comma-separate them

let sum: [Int] -> Int = flip(reduce) <| (+) <| 0

Since Swift functions can also be applied to tuples of their arguments, you can also use |> and <| with binary, ternary, etc. functions just by placing a tuple on the other side:

(1, 2) |> (+) // => 3

curry

Currying takes a function of >1 parameter and returns a function of one parameter which returns a function of one parameter, and so on. That is, given (T, U) -> V, currying returns T -> U -> V.

This is particularly useful when making more interesting functions such as <|.

flip

Faux operator sectioning using <| might be a little surprising using non-commutative operators like - and /: (-) <| 1 means { 1 - $0 }, which is very different from { $0 - 1 }. You can use flip to produce the latter:

map([1, 2, 3], (-) <| 1) // => [0, -1, -2]
map([1, 2, 3], flip(-) <| 1) // => [0, 1, 2]

&&&

Optional has a map method which is just what you need when you want to apply a function to a value if non-nil, or return nil otherwise. When you have two Optional values, you can use &&& to combine them:

let (x: Int?, y: Int?) = (2, 2)
(x &&& y).map(+) // => .Some(4)

swap

Swift’s tuples are very convenient, but sometimes when you get one, it’s the wrong way around. swap does to tuples what flip does to functions: it reverses their order.

map(enumerate("hello"), swap) // => [(h, 0), (e, 1), (l, 2), (l, 3), (o, 4)]

first and second

Getting one value from a tuple is a common operation that can be expressed with first and second functions. Operators provide first and second values of two-elements tuple accordingly.

[(0,0), (5, 1), (9, 2)].map(second) // => [0, 1, 2]

Documentation

Full API documentation is in the source.

Integration

  1. Add this repository as a submodule and check out its dependencies, and/or add it to your Cartfile if you’re using carthage to manage your dependencies.
  2. Drag Prelude.xcodeproj into your project or workspace.
  3. Link your target against Prelude.framework.
  4. Application targets should ensure that the framework gets copied into their application bundle. (Framework targets should instead require the application linking them to include Prelude.)

Or use the Swift package manager and add this to your Package.swift file:

  ...
  dependencies: [
    ...  
    .package(url: "https://github.com/robrix/Prelude", "3.0.0" ..< "4.0.0")
  ],
  targets: [
    ...
    .target(
        name: "<YourTargetName>",
        dependencies: ["Prelude"]),
  ]

More Repositories

1

RXCollections

Obsolete—use https://github.com/robrix/Reducers instead.
Objective-C
477
star
2

Madness

Recursive Descent Into Madness
Swift
291
star
3

Postmodern-Programming

236
star
4

Box

Swift µframework of the ubiquitous Box<T> & MutableBox<T> reference types, for recursive value types & misc. other purposes.
Swift
215
star
5

Either

Swift µframework of Either, which represents two alternatives.
Swift
150
star
6

Reducers

Clojure-inspired reducers for Cocoa & Cocoa Touch.
Objective-C
138
star
7

Set

An implementation of Multiset and PredicateSet in Swift.
Swift
112
star
8

RXFutures

Race-free completion and cancellation of asynchronous work.
Objective-C
89
star
9

path

A lambda calculus to explore type-directed program synthesis.
Haskell
82
star
10

Grid

Rational window management
Objective-C
80
star
11

Hammer

Parsing and pattern matching in Objective-C
Objective-C
75
star
12

starlight

spaceships in space
Haskell
71
star
13

Traversal

Enumeration & iteration of collections in Swift.
Swift
58
star
14

Obstruct

Block introspection and interaction
C
47
star
15

Memo

Swift µframework of Memo, a lazily memoized value.
Swift
45
star
16

semilattices

join and meet semilattices, lower and upper bounds.
Haskell
43
star
17

Lagrangian

On the dark side of the sun.
Objective-C
42
star
18

RXPreprocessing

A variety of utilities for the C preprocessor.
C
38
star
19

Many-Types-Make-Light-Work

Don’t subclass.
35
star
20

Haxcessibility

Hackery via the AX (Accessibility) APIs
Objective-C
33
star
21

ui-effects

An experiment towards a UI programming model inspired by algebraic effects.
Haskell
30
star
22

RXConcreteProtocol

Mix-ins for Objective-C
Objective-C
25
star
23

List

Singly-linked lists in Swift.
Swift
25
star
24

Hammer.swift

When all you have is a parser, everything looks like a language.
Swift
24
star
25

freer-cofreer

freer monads and cofreer comonads.
Haskell
21
star
26

languages-all-the-way-down

outline & examples for my ZuriHac 2020 talk, Languages All the Way Down
Haskell
20
star
27

Project-Templates

Xcode project templates, especially for µframework development.
Swift
20
star
28

sequoia

classical sequent calculus, embedded in Haskell
Haskell
20
star
29

A-Swiftly-Tilting-Parser

Talk about the derivative of parser combinators in ObjC & Swift
19
star
30

Manifold

Another experiment in dependently typed languages, this time with some quantitative type theory smooshed in.
Haskell
18
star
31

silkscreen

Prettyprinting transformers for rainbow parens, precedence, etc.
Haskell
16
star
32

abstract-interpretation

Experiments in abstracting definitional interpreters
Haskell
16
star
33

Delay

µframework for lazy evaluation in Swift.
Swift
16
star
34

tilec

Sometimes when I feel sad I implement a dependently typed lambda calculus.
Haskell
15
star
35

Auspicion

Convenient LLVM compiler API for Objective-C.
Swift
15
star
36

objectbinder

Bind arbitrary objects’ properties without writing new IB3 plugins.
Objective-C
13
star
37

Pork

PDF → other
Swift
12
star
38

isometry

programmatic voxels
Haskell
12
star
39

RXAssertions

Smarter assertion macros for your OCUnit tests.
Objective-C
12
star
40

NSFastEnumeration-or-Consequences

NSFastEnumeration and lazy evaluation—or doom!
10
star
41

surface

Dependently-typed language w/ little to say for itself
Haskell
10
star
42

dotfiles

the very dottest of files 💻
Shell
9
star
43

dragon

Renders iterations of the dragon curve to SVG
Haskell
9
star
44

TaPL

Types and Programming Languages notes and exercises
Swift
9
star
45

Extraction

A tool to audio tracks from QuickTime files, e.g. for YouTube → iTunes use
Objective-C
9
star
46

credit-card-validation

Credit card number validation as functional–style Swift.
Swift
8
star
47

RXSynchronously

A very convenient way to wait for asynchronous work to complete.
Objective-C
8
star
48

semirings-modules

Semirings, with and without additive/multiplicative identities, and R-modules.
Haskell
7
star
49

Loyalist

Algebraic autolayout
Swift
7
star
50

RXVersionedUndoManager

An NSUndoManager subclass which stores commits to a git branch.
Objective-C
6
star
51

interval-functor

General purpose intervals of functors.
Haskell
6
star
52

xcode-light

A lightweight Xcode-integration bundle for TextMate. Clean and fresh inside and out!
Ruby
6
star
53

Navel-Gazing

Introspection at its worst.
Objective-C
6
star
54

RXVisitor

A convenient implementation of Visitor pattern for Objective-C collections.
Objective-C
6
star
55

language-haskell-ast

Generic interface over the AST provided by haskell-src-exts
Haskell
5
star
56

seq

a µµ̃ calculus with pretty-printing and evaluating interpreters
Haskell
5
star
57

RXTraits

Trait-ish decorators, as an alternative to RXConcreteProtocol.
Objective-C
5
star
58

text-gl

Text, rendered with OpenGL.
Haskell
5
star
59

derivative-parsing

Parsing with Derivatives, in Haskell, with GADTs.
Haskell
5
star
60

forthward

A toy concatenative language to explore K ( http://k-framework.org )
Ruby
5
star
61

effects-sequences

Extensible effects à la Oleg, but with fancier effect sets.
Haskell
5
star
62

Lagrangian.swift

Unit tests from the dark side of the sun.
Swift
4
star
63

robrix.github.io

Words by me
HTML
4
star
64

BlendColourPicker

A colour picker for Mac OS X 10.5+; blend two colours to get a third.
Objective-C
4
star
65

RXJSONCoder

An experimental implementation of JSON encoding/decoding in ObjC using NSCoder/NSCoding
Objective-C
4
star
66

elab

Dependently-typed language to experiment with An Algebraic Approach to Typechecking and Elaboration
Haskell
4
star
67

RXPaths

Serialize and deserialize paths to an SVG path command-compatible format
Objective-C
4
star
68

Y

The Y combinator, implemented in Ruby and Objective-C.
Objective-C
3
star
69

semiring-parsing

Parsing in semirings
Haskell
3
star
70

Relation

Finitary relations in Swift.
C++
3
star
71

meconation

For Micah
Objective-C
3
star
72

ns

Quick access to ADC docset documentation: `ns array`, `ui view`, `cf type`
3
star
73

Halftone

I wanted to make something pretty.
Objective-C
3
star
74

q

q is for query
Ruby
3
star
75

build-stack

Build stack packages from Atom via https://atom.io/packages/build
JavaScript
3
star
76

proficiency

Haskell profile visualization tools.
Haskell
2
star
77

spline

Generative SVG experiments
Haskell
2
star
78

Focus

An experimental language of little interest to anyone.
C
2
star
79

continuations

Continuations, CPS, co-functions, and combinators for working with them
Haskell
2
star
80

RXLazyEnumerations

Lazy enumerations of files (as characters) and generators.
Objective-C
2
star
81

Xcode-Templates

My Xcode Templates, just because. You will probably not care about this.
Objective-C
2
star
82

Quantificate

Measurements and conversions in ObjC
2
star
83

distribution

Probability distributions à la Deriving a Probability Density Calculator by Wazim Mohammed Ismail & Chung-chieh Shan http://homes.soic.indiana.edu/ccshan/rational/pearl.pdf
Haskell
2
star
84

parallel-incremental

Haskell
2
star
85

glitch

An increasingly charming view of your git repositories written with sinatra, grit, and love; just add browser/RSS reader.
Ruby
2
star
86

Drgn

A Cocoa app which draws the dragon curve. cf http://en.wikipedia.org/wiki/Dragon_curve
Objective-C
2
star
87

deterministic-parsing

An experiment in deterministic parsing of LL(1) grammars
Haskell
1
star
88

complexity-analysis

Sized type elaboration, eventually via abstract interpretation.
Haskell
1
star
89

crocus

a datalog
Haskell
1
star
90

memory

Outsourcing my memory
1
star
91

hello-world

Hello, world! ❤️
1
star
92

raytracer

A toy raytracer in Haskell
Haskell
1
star
93

higher-order

Higher-order (type-indexed) analogues of various typeclasses, and machinery over them.
Haskell
1
star
94

RXAllocator

A dumb bump pointer allocator designed dumbly to be as dumb as dumbness itself.
Objective-C
1
star
95

-

The ω function is a non-recursive, non-terminating function; this is an implementation of it in Objective-C.
Objective-C
1
star
96

Monochrome-motemplate

My *.motemplate files. Nothing to see here, move along folks.
1
star
97

Arborescence

arborescence, n. a quality of being treelike in growth or appearance.
C
1
star
98

cabal-action

GitHub Actions for cabal new-build
Dockerfile
1
star
99

lambdaft

Haskell
1
star
100

synth

Audio synthesis and sequencing
Haskell
1
star