elm - 在 Elm 中实现我自己的 toString 的正确方法是什么

标签 elm

在 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/

相关文章:

random - elm 中 Random.initialSeed 的预期行为是什么(v0.15)

elm - 如何在Elm中打印列表?

css - 使用(或不使用)webpack 在 .elm 文件中导入 css/style 文件

dictionary - 从记录列表生成字典

Elm 找不到依赖项中的模块

events - 事件触发时获取 ID 属性 (elm v0.19.1)

functional-programming - 用 "as"字解构 Elm 中的记录

Elm - 如何检测当前焦点

Elm:如何将 Html FooMsg 转换为 Html Msg

html - Elm - 不要转义 html 字符串