File tree Expand file tree Collapse file tree 2 files changed +56
-0
lines changed
Expand file tree Collapse file tree 2 files changed +56
-0
lines changed Original file line number Diff line number Diff line change 88
99/// MARK: Array extensions
1010
11+ public enum ArrayMatcher < A> {
12+ case Nil
13+ case Cons( A , [ A ] )
14+ }
15+
16+ /// Destructures a list into its constituent parts.
17+ ///
18+ /// If the given list is empty, this function returns .Empty. If the list is non-empty, this
19+ /// function returns .Cons(hd, tl)
20+ public func match< T> ( l : [ T ] ) -> ArrayMatcher < T > {
21+ if l. count == 0 {
22+ return . Nil
23+ } else if l. count == 1 {
24+ return . Cons( l [ 0 ] , [ ] )
25+ }
26+ let hd = l [ 0 ]
27+ let tl = Array < T > ( l [ 1 ..< l. count] )
28+ return . Cons( hd, tl)
29+ }
30+
31+ /// Returns the first element in the list, or None if the list is empty.
32+ public func head< A> ( l : [ A ] ) -> Optional < A > {
33+ switch match ( l) {
34+ case . Nil:
35+ return . None
36+ case . Cons( let x, _) :
37+ return . Some( x)
38+ }
39+ }
40+
41+ /// Returns the tail of the list, or None if the list is empty.
42+ public func tail< A> ( l : [ A ] ) -> Optional < [ A ] > {
43+ switch match ( l) {
44+ case . Nil:
45+ return . None
46+ case . Cons( _, let xs) :
47+ return . Some( xs)
48+ }
49+ }
50+
51+ /// Adds an element to the front of a list.
52+ public func cons< T> ( lhs : T , var rhs : [ T ] ) -> [ T ] {
53+ rhs. insert ( lhs, atIndex: 0 )
54+ return rhs
55+ }
56+
1157/// Safely indexes into an array by converting out of bounds errors to nils.
1258public func safeIndex< T> ( array : Array < T > ) ( i : Int ) -> T ? {
1359 return indexArray ( array, i)
Original file line number Diff line number Diff line change @@ -190,6 +190,16 @@ public struct Set<A : Hashable> {
190190 public func reduce< B> ( f : ( B , A ) -> B , initial : B ) -> B {
191191 return array. reduce ( initial, combine: f)
192192 }
193+
194+ /// Returns all elements of the receiver in a List in no particular order.
195+ public func toList( ) -> List < A > {
196+ return self . reduce ( flip ( List . cons) , initial: List ( ) )
197+ }
198+
199+ /// Returns all elements of the receiver in an Array in no particular order.
200+ public func toArray( ) -> Array < A > {
201+ return self . reduce ( flip ( cons) , initial: [ ] )
202+ }
193203}
194204
195205extension Set : ArrayLiteralConvertible {
You can’t perform that action at this time.
0 commit comments