Some basic tools for functional programming
blackhole
Simply functions which take a value and do nothing with it. Useful for testing and mocks. For example:
stuff.forEach(blackhole)
null
Like blackhole
, this simply functions which take a value and do nothing with it. Unlike blackhole
, this will always be optimized away in production code. Useful for giving to functions which demand a callback, when you don't have anything to do after it calls back.
For example:
myObject.someAsyncFunction(onComplete: null)
call
A utility function which simply calls the given function. This is useful for compressing higher-order functions. For example:
let someFunctions: [BlindCallback] = [
{ print("Hello") },
{ print("World!") },
]
someFunctions.forEach(call)
curry
Converts a non-currying function into a currying function. For example:
let add = curry(+)
[1, 2, 3, 4].map(add(4)) // [5, 6, 7, 8]
echo
Simply returns what it's given. This is useful for reusing the input of higher-order functions. For example:
let withoutNils = arrayOfOptionals.compactMap(echo)
It's also useful for flattening collections of generators. For example:
let values = generators.map(echo)
And for providing a predictable test function. For example:
Lazy(initializer: echo("Foo"))
constant
Simply returns a function with a constant output. This is useful when making a test/preview where you always want the same output.
Lazy(initializer: constant("Foo"))
MyView(textTranslator: constant("Bar")) // imagining `textTranslator` is like `(String) -> String`
!
Converts any function which returns a Bool
into one which returns the opposite value.
For example:
public extension Array {
func exclude(by filter: @escaping Transformer<Element, Bool>) -> some LazySequenceProtocol {
self.lazy.filter(!mapper)
}
}
Some typealiases for common functions:
BlindCallback
and ThrowingBlindCallback
Callback
and ThrowingCallback
Transformer
and ThrowingTransformer
map
functionFilter
and ThrowingFilter
filter
functionGenerator
and ThrowingGenerator
@autoclosure
Reducer
and ThrowingReducer
reduce
functionAllocationReducer
and ThrowingAllocationReducer
reduce
function. Often slower than Reducer
.Combinator
and ThrowingCombinator
CurriedCombinator
link |
Stars: 0 |
Last commit: 25 weeks ago |
This release brings three new function generators:
echo(_:)
- A new echo
function which creates and returns a function which only ever returns the value you gave the echo
functionconstant(_:)
- Two functions which always return the same value: one just like the above echo
function (purely alias for clarity), and one which creates a non-transformer which ignores its input always returns the same value!
- Creates a function which simply inverts the output of the function after the exclamation pointSee the Readme for examples!
curry
function public
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics