在 Elm 中,获取我的模型并实现 toString 函数的正确方法是什么?
我正在寻找的类型是 toString : Model -> String
,我可以用 toStr : Model -> String
的类型制作类似的功能但我想我希望函数被称为 toString
.
示例程序(Coin Changer kata):
module CoinChanger where
import Html exposing (..)
import StartApp.Simple as StartApp
import Signal exposing (Address)
import Html.Attributes exposing (..)
import Html.Events exposing (on, targetValue)
import String
---- MAIN ----
main =
StartApp.start
{
model = emptyModel
,update = update
,view = view
}
---- Model ----
type alias Model =
{
change : List Int
}
emptyModel : Model
emptyModel =
{
change = []
}
---- VIEW ----
toStr : Model -> String
toStr model =
model.change
|> List.map (\coin -> (toString coin) ++ "¢")
|> String.join ", "
view : Address String -> Model -> Html
view address model =
div []
[
input
[
placeholder "amount to make change for"
, on "input" targetValue (Signal.message address)
, autofocus True
-- style
]
[]
, div []
[
text (toStr model)
]
]
---- UPDATE ----
changeFor : Int -> List Int
changeFor amount =
[ 25, 10, 5, 1 ]
|> List.foldl
(\coin (change, amount)
-> ( change ++ List.repeat (amount // coin) coin
, amount % coin)
)
([], amount)
|> fst
update : String -> Model -> Model
update change model =
{ model | change =
case String.toInt change of
Ok amount
-> changeFor amount
Err msg
-> []
}
我认为正确的方法是调用函数
toString
,但这给了我来自编译器的以下错误:Detected errors in 1 module. -- TYPE MISMATCH ----------------------------------------------- CoinChanger.elm
The type annotation for
toString
does not match its definition.42│ toString : Model -> String ^^^^^^^^^^^^^^^ The type annotation is saying:
{ change : List Int } -> String
But I am inferring that the definition has this type:
{ change : List { change : List Int } } -> String
将函数重命名为
toStr
(或不叫 toString
的东西)解决了这个问题,但似乎是错误的。这样做的正确方法是什么?
最佳答案
问题是,调用你的函数 toString
,您将覆盖 toString
Basics
的功能您在第 45 行使用的模块。
为避免这种情况,您需要导入 Basics
模块和使用Basics.toString
而不是简单的toString
消除歧义
关于elm - 在 Elm 中实现我自己的 toString 的正确方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36679378/