Skip to content

Instantly share code, notes, and snippets.

@shoheiyokoyama
Last active February 27, 2017 03:14
Show Gist options
  • Save shoheiyokoyama/21fffc6797a54b29a6cd00340577dae5 to your computer and use it in GitHub Desktop.
Save shoheiyokoyama/21fffc6797a54b29a6cd00340577dae5 to your computer and use it in GitHub Desktop.
Swiftエンジニアの高階関数実践 ref: http://qiita.com/shoheiyokoyama/items/8c855e8f5caf7d136027
applyTwice :: (a -> a) -> a -> a
applyTwice f x = f (f x)
Prelude> applyTwice (+3) 10
16
Prelude> applyTwice (3:) [2]
[3, 3, 2]
let repeateString = curry { (count: Int, element: String) -> [String] in
Array(repeating: element, count: count)
}
let threeArray = repeateString(3)
threeArray("Swift") // ["Swift", "Swift", "Swift"]
threeArray("Haskell") // ["Haskell", "Haskell", "Haskell"]
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
Prelude> map (+2) [1, 2, 3, 4]
[3, 4, 5, 6]
Prelude> map (replicate 3) [1..3]
[[1,1,1],[2,2,2][3,3,3]]
zipWith' :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith' _ [] _ = []
zipWith' _ _ [] = []
zipWith' f (x:xs) (y:ys) = f x y : zipWith' f xs ys
Prelude> zipWith' (+3) 10
16
Prelude> zipWith' (3:) [2]
[3, 3, 2]
func double(_ array: [Int]) -> [Int] {
var result: [Int] = []
for x in array {
result.append( x * 2)
}
return result
}
double([3, 4]) // [6, 8]
func map<Element, T>(_ array: [Element], transform: (Element) -> T) -> [T] {
var result: [T] = []
for x in array {
result.append(transform(x))
}
return result
}
map([2, 3]) { $0 * 2 } // [4, 6]
map([8, 4]) { $0 / 2 } // [4, 2]
map(["Swit", "swif"]) { $0 + "t" } // ["Swift", "swift"]
func filter<Element>(_ array: [Element], includeElement: (Element) -> Bool) -> [Element] {
var result: [Element] = []
for x in array where includeElement(x) {
result.append( x)
}
return result
}
filter([3, 4, 5]) { $0 > 3 } //[4, 5]
func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { x in
{ y in f(x, y) }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment