首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Elm Colon =算子

Elm Colon =算子
EN

Stack Overflow用户
提问于 2017-07-26 16:39:09
回答 1查看 181关注 0票数 1

在试图解码更大的json值时,我在Json-Decode-Extra库中遇到了以下代码。(位于这里)

代码语言:javascript
复制
import Date (Date)

type alias User =
  { id                : Int
  , createdAt         : Date
  , updatedAt         : Date
  , deletedAt         : Maybe Date
  , username          : Maybe String
  , email             : Maybe String
  , fullname          : Maybe String
  , avatar            : Maybe String
  , isModerator       : Bool
  , isOrganization    : Bool
  , isAdmin           : Bool
  }

metaDecoder : (Int -> Date -> Date -> Maybe Date -> b) -> Decoder b
metaDecoder f = f
  `map`      ("id"        := int)
  `apply` ("createdAt" := date)
  `apply` ("updatedAt" := date)
  `apply` ("deletedAt" := maybe date)

userDecoder : Decoder User
userDecoder = metaDecoder User
  `apply` ("username"          := maybe string)
  `apply` ("email"             := maybe string)
  `apply` ("fullname"          := maybe string)
  `apply` ("avatar"            := maybe string)
  `apply` ("isModerator"       := bool)
  `apply` ("isOrganization"    := bool)
  `apply` ("isAdmin"           := bool)

但是,我经常遇到:=操作符的编译器错误。这是在哪里定义的?JSON解码教程不会显式地导入这个操作符。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-26 16:44:18

在ELM0.18中,将:=操作符替换为Json.Decode.field,并删除infix操作符的backticks。

您使用的是未更新为Elm 0.18的包(想像机/Elm-json-加号)。

考虑切换到使用Elm社区维护的包:elm-community/json-extra。您可以使用andMap而不是apply。下面是升级到新库和Elm 0.18的示例代码:

代码语言:javascript
复制
import Date exposing (Date)
import Json.Decode exposing (..)
import Json.Decode.Extra exposing (andMap, date)

metaDecoder : (Int -> Date -> Date -> Maybe Date -> b) -> Decoder b
metaDecoder f =
    succeed f
        |> andMap (field "id" int)
        |> andMap (field "createdAt" date)
        |> andMap (field "updatedAt" date)
        |> andMap (field "deletedAt" (maybe date))

userDecoder : Decoder User
userDecoder =
    metaDecoder User
        |> andMap (field "username" (maybe string))
        |> andMap (field "email" (maybe string))
        |> andMap (field "fullname" (maybe string))
        |> andMap (field "avatar" (maybe string))
        |> andMap (field "isModerator" bool)
        |> andMap (field "isOrganization" bool)
        |> andMap (field "isAdmin" bool)

注意,elm-community/json-extra包还导出一个infix操作符|:,它是andMap的infix版本。您可以使用它来使代码更加简洁。例如:

代码语言:javascript
复制
metaDecoder : (Int -> Date -> Date -> Maybe Date -> b) -> Decoder b
metaDecoder f =
    succeed f
        |: field "id" int
        |: field "createdAt" date
        |: field "updatedAt" date
        |: field "deletedAt" (maybe date)
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45332849

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档