Elm :模型中的初始化集

Elm : initialise set in the model

我是 Elm 的新手。我想做的是我试图用一个集合而不是一个列表来初始化模型,但是鉴于 elm 没有任何集合的初始化器(这很遗憾,如果它是 #{1,2 就好了,3},就像在 Clojure 中一样),这是有问题的。

有了代码(Elm教程代码,稍微修改了一下),我正在努力

main =
  App.program
    { init = init "cats"
    , view = view
    , update = update
    , subscriptions = subscriptions
    }



-- MODEL


type alias Model =
  { topic : String
  , gifUrl : String
  , error : String
  , history : Set String
  }


init : String -> (Model, Cmd Msg)
init topic =
  ( Model topic "waiting.gif" "" Set.fromList([topic])
  , getRandomGif topic
  )

这会引发编译器错误:

Function `Model` is expecting 4 arguments, but was given 5.

这很奇怪,因为这不会在 Elm repl 中引发错误,并且在大多数情况下是有效代码。

我该如何实现?

问题源于您使用了括号。

Model topic "waiting.gif" "" Set.fromList([topic])
-- is the same as:
Model topic "waiting.gif" "" Set.fromList [topic] 

您不需要在 Elm 中将参数括在括号中,但您确实需要将 Set.fromList [topic] 的整个第四个参数括起来,以便编译器知道它是单个参数。把它改成这个,你应该已经准备好了:

Model topic "waiting.gif" "" (Set.fromList [topic])