Skip to content

Instantly share code, notes, and snippets.

@d-date
Created September 3, 2018 20:32
Show Gist options
  • Save d-date/5f72351c5d516ec805bf0a621ec1ee33 to your computer and use it in GitHub Desktop.
Save d-date/5f72351c5d516ec805bf0a621ec1ee33 to your computer and use it in GitHub Desktop.
How to map value in tuple #CodePiece #tryswiftnyc
func mapFirst<A, B, C>(
_ f: @escaping (A) -> B)
-> ((A, C)) -> (B, C) {
return { pair in (f(pair.0), pair.1) }
}
let incrFirst2: ((Int, String)) -> (Int, String) = mapFirst(incr)
pair |> mapFirst(incr)
func mapSecond<A, B, C>(
_ f: @escaping (A) -> B)
-> ((C, A)) -> (C, B) {
return { pair in (pair.0, f(pair.1)) }
}
pair
// |> mapFirst(incr)
// >>> mapFirst(square)
// >>> mapFirst(String.init)
|> mapFirst(incr >>> square >>> String.init)
>>> mapSecond { $0.count }
mapFirst(incr)
>>> mapFirst(square)
>>> mapFirst(String.init)
>>> mapSecond { (str: String) in
str.count }
let nested = ("Hello", (42, "World"))
nested |> mapSecond { second in
second |> mapFirst { first in
incr(first)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment