Skip to content

Instantly share code, notes, and snippets.

View surajsau's full-sized avatar
🙇‍♂️
よろしくお願いします!

Suraj Kumar Sau surajsau

🙇‍♂️
よろしくお願いします!
View GitHub Profile
fun add(a: Int, b: Int, c: Int) = a + b + c
fun wrap(f: (Int, Int, Int) -> Int) = { x: Int -> { y: Int -> { z: Int -> f(x, y, z) }}}
val result = Functor.Something(1).map(wrap(::add)) // Something({ y -> { z -> add(1, y, z) }})
.apply(Functor.Something(2)) // Something({z -> add(1, 2, z) })
.apply(Functor.Something(3)) // Something(6)
fun add3() = { a: Int -> a + 3 }
val wrappedFunction = Functor.Something(add3()) //Something({it -> it + 3})
val wrappedValue = Functor.Something(2) //Something(2)
/*
apply() = Functor.Something(2).map({it -> it + 3})
*/
val result = wrappedValue.apply() //Something(5)
//Extension function for type context wrapped function of type: (T) -> S
fun<T, S> Functor<(T) -> S>.apply(f: Functor<T>): Functor<S> = when(this) {
is Nothing -> this
is Something -> f.map(this.value) //this.value is the unwrapped function itself
}
fun add3(x: Int) = x + 3 //our normal function
val something = Functor.Something(3)
val altered = something.map { add3(it) }.map { add3(it) } //returns Something(9)
val nothing = Functor.Nothing
val alteredNothing = nothing.map { add3(it) } //returns Nothing
sealed class Functor<out T> {
object Nothing: Functor<kotlin.Nothing>()
data class Something<out T>(val value: T): Functor<T>()
inline fun<S> map(f: (T) -> S): Functor<S> = when(this) {
is Nothing -> this
is Something -> Something(f(this.value))
}
struct APIService {
@GET(url: "https://swapi.co/api/films")
static var getFilms: Observer<Films>
}
APIService.getFilms { (response) in
//response is the same received in Alamofire's completionHandler
..
@propertyWrapper
struct GET<T: Decodable> {
private var url: URL
init(url: String) {
self.url = URL(string: url)!
}
var wrappedValue: Observer<T> {
get {
typealias Observer<T: Decodable> = (_ completionhandler: @escaping (DataResponse<T, AFError>) -> Void) -> ()
struct APIService {
@GET(url: "https://swapi.co/api/films")
static var getFilms: Service<Films>
}
func fetchFilms() {
AF.request("https://swapi.co/api/films")
.validate()
.responseDecodable(of: Films.self) { (response) in
..
}
}
func searchStarships(for name: String) {