|
| 1 | +public func uncons<A>(_ xs: [A]) -> (A, [A])? { |
| 2 | + guard let x = xs.first else { return nil } |
| 3 | + return (x, Array(xs.dropFirst())) |
| 4 | +} |
| 5 | + |
| 6 | +public func <¢> <A, B> (f: (A) -> B, xs: [A]) -> [B] { |
| 7 | + return xs.map(f) |
| 8 | +} |
| 9 | + |
| 10 | +public func <*> <A, B> (fs: [(A) -> B], xs: [A]) -> [B] { |
| 11 | + return fs.flatMap { f in xs.map(f) } |
| 12 | +} |
| 13 | + |
| 14 | +public func foldMap<A, M: Monoid>(_ f: @escaping (A) -> M) -> ([A]) -> M { |
| 15 | + return { xs in |
| 16 | + xs.reduce(M.e) { accum, x in accum <> f(x) } |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +public func partition<A>(_ p: @escaping (A) -> Bool) -> ([A]) -> ([A], [A]) { |
| 21 | + return { xs in |
| 22 | + xs.reduce(([], [])) { accum, x in |
| 23 | + p(x) ? (accum.0 + [x], accum.1) : (accum.0, accum.1 + [x]) |
| 24 | + } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +public func elem<A: Equatable>(_ x: A) -> ([A]) -> Bool { |
| 29 | + return { xs in xs.contains(x) } |
| 30 | +} |
| 31 | + |
| 32 | +public func elem<A: Equatable>(of xs: [A]) -> (A) -> Bool { |
| 33 | + return { x in xs.contains(x) } |
| 34 | +} |
| 35 | + |
| 36 | +public func zipWith<A, B, C>(_ f: @escaping (A, B) -> C) -> ([A]) -> ([B]) -> [C] { |
| 37 | + return { xs in |
| 38 | + return { ys in |
| 39 | + return zip(xs, ys).map { f($0.0, $0.1) } |
| 40 | + } |
| 41 | + } |
| 42 | +} |
| 43 | + |
| 44 | +public func sorted<A>(by f: @escaping (A, A) -> Bool) -> ([A]) -> [A] { |
| 45 | + return { xs in |
| 46 | + xs.sorted(by: f) |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +public func lookup<A: Equatable, B>(_ x: A) -> ([(A, B)]) -> B? { |
| 51 | + return { pairs in |
| 52 | + pairs.first { pair in pair.0 == x }.map(second) |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +public func catOptionals<A>(_ xs: [A?]) -> [A] { |
| 57 | + return xs |> mapOptional(id) |
| 58 | +} |
| 59 | + |
| 60 | +public func mapOptional<A, B>(_ f: @escaping (A) -> B?) -> ([A]) -> [B] { |
| 61 | + return { xs in |
| 62 | + xs.flatMap(f) |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +public func replicate<A>(_ n: Int) -> (A) -> [A] { |
| 67 | + return { a in (1...n).map(const(a)) } |
| 68 | +} |
0 commit comments