Upgrade to Pro — share decks privately, control downloads, hide ads and more …

nel

to4iki
December 09, 2018

 nel

to4iki

December 09, 2018
Tweet

More Decks by to4iki

Other Decks in Programming

Transcript

  1. e.g. 2 /// GraphQL type’s fields enum UserField: String {

    case id, name, email } /// build up a query func query(_ fields: Set<UserField>) -> String { return (["{\n"] + fields.map { " \($0.rawValue)\n" } + ["}\n"]) .joined() } 6
  2. e.g. 2 ! request success query([.id, .name]) // { //

    name // id // } ! request runtime-error query([]) // { // } 7
  3. NonEmptyList2 /// a data type which represents a non empty

    list of A. /// single element (head) and optional structure (tail). struct NonEmptyArray<T> { let head(T) let tail: [T] } 2 Swift͸ඪ४ܕͰList͕ଘࡏ͠ͳ͍ͷͰɺArrayΛࣄྫʹͯ͠ѻ͏ 13
  4. other solution enum NonEmptyArray<T> { case single(T) indirect case cons(T,

    NonEmptyArray<T>) } // [1, 2, 3] NonEmptyArray.cons(1, .cons(2, .single(3))) 15
  5. NonEmpty<C: Collection> struct NonEmpty<C: Collection> { var head: C.Element var

    tail: C init(_ head: C.Element, _ tail: C) { self.head = head self.tail = tail } } 17
  6. typealias NonEmptyArray<T> = NonEmpty<Array<T>> typealias NonEmptySet<T> = NonEmpty<Set<T>> where T:

    Hashable typealias NonEmptyDictionary<K, V> = NonEmpty<Dictionary<K, V>> where K: Hashable // etc... 18
  7. ! overload non-nil property extension NonEmpty { /// overload non-nil

    var first: C.Element { return self.head } } extension NonEmpty where C: BidirectionalCollection { /// overload non-nil var last: C.Element { return self.tail.last ?? self.head } } 21
  8. Array let xs = [1, 2, 3] xs.first.map { $0

    + 1 } ?? 0 xs.last! + 1 // unsafe ! NonEmptyArray let xs = NonEmptyArray(1, 2, 3) xs.first + 1 xs.last + 1 22
  9. Other lang • Haskel: Data.List.NonEmpty • https://hackage.haskell.org/package/semigroups-0.16.0.1/docs/Data-List- NonEmpty.html • Elm:

    List.Nonempty • https://package.elm-lang.org/packages/mgold/elm-nonempty-list/3.1.0/List- Nonempty • scalaz / cats • functional java • etc... 24
  10. Validation(Nel) • Monad • Applicative Functor • https://typelevel.org/cats/datatypes/validated.html /// `Result`

    with success-value, `nel` as the failure type. enum Validated<Value, E: Swift.Error> { case valid(Value) case invalid(NonEmptyArray<E>) } 26
  11. Kotlin: arrow.Validated • https://arrow-kt.io/docs/datatypes/validated/ @higherkind sealed class Validated<out E, out

    A> : ValidatedOf<E, A> { data class Valid<out A>(val a: A) : Validated<Nothing, A>() data class Invalid<out E>(val e: E) : Validated<E, Nothing>() } 27
  12. e.g let validatedPassword: Validated<String, PasswordInputError> ... switch validatedPassword { case

    .valid(let value): print(value) case .invalid(let errors): // e.g. preset `errors.first` messages } 28
  13. Conclusion • Ϧετ͸ ۭ or ۭͰ͸ͳ͍ͷ 2छྨͷঢ়ଶ͕ଘࡏ͢Δ • NonEmpty<C: Collection>

    ʹΑΓɺܕϨϕϧͰ ۭͰ͸ͳ͍ ঢ়ଶΛ୲อ͢Δ͜ͱ͕Ͱ͖Δ • ڊਓͷݞ(ଟݴޠͰͷ࣮૷ྫ)ʹ৐͍ͬͯ͜͏ 29