美文网首页
Functional

Functional

作者: 幸运的小强本人 | 来源:发表于2016-03-06 20:31 被阅读6次

重载了几个运算符,了解运算符重载的概念,同时了解在JSON 处理中的一些逻辑:

infix operator >>> {
  // bind
  associativity left precedence 150
}

infix operator <^> {
  // Functor's fmap(usually <$>)
  associativity left
}

infix operator <*> {
  // Applicative's apply
  associativity left
}

func >>><A, B>(a: A?, f: A->B?)->B? {
    if let x = a {
        return f(x)
    }else {
        return .None
    }
}

func >>><A, B>(a:Result<A>, f:A-> Result<B>)->Result<B> {
    switch a {
        case let .Value(x): return f(x.value)
        case let .Error(error): return .Error(error)
    }
}

func <^><A, B>(f: A->B, a: A?)->B? {
    if let x = a {
        return f(x)
    }else {
        return .None
    }
}

func <*><A, B>(f:(A->B)?, a: A?)->B? {
    if let x = a {
        if let fx = f {
            return fx(x)
        }
    }

    return .None
}

相关文章

网友评论

      本文标题:Functional

      本文链接:https://www.haomeiwen.com/subject/eayakttx.html