Last active
August 29, 2015 14:02
-
-
Save jasonsperske/d99f271287dd62e01d0b to your computer and use it in GitHub Desktop.
Getting aquainted with a new langauge. Really wish there was a splatter operator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func car<T>(l: Array<T>?) -> T? { | |
if l == nil || l!.count <= 0 { | |
return nil | |
} else { | |
return l![0] | |
} | |
} | |
func cdr<T>(l: Array<T>?) -> Array<T>? { | |
if l == nil || l!.count <= 1 { | |
return nil | |
} else { | |
return Array<T>(l![1..l!.count]) | |
} | |
} | |
var beverly_hills = [9,0,2,1,0] | |
car(beverly_hills) //9 | |
cdr(beverly_hills) //[0,2,1,0] | |
var ingredients = ["sugar", "flower", "eggs", "water"] | |
car(ingredients) //"sugar" | |
cdr(ingredients) //["flower", "eggs", "water"] | |
//Almost empty | |
car([3.14]) // 3.14 | |
cdr([3.14]) //nil | |
//Empty | |
car(Double[]()) //nil | |
cdr(Double[]()) //nil | |
//A summing function implemented using: | |
func sum(numbers: Array<Int>?, answer: Int = 0) -> Int { | |
let first = car(numbers) | |
if first == nil { | |
return answer | |
} else { | |
return answer + sum(cdr(numbers), answer: first!) | |
} | |
} | |
sum([1,2,3,4,5]) //15 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Allowed for the passing of optional arrays so I could implement a sum function.