使用列表的Elm多计数器代码
我是Elm的新手,以前我在做使用列表的Elm多计数器代码,elm,Elm,我是Elm的新手,以前我在做React,Redux,ES6 需要帮助,使用数组而不是列表优化下面的反例。 尝试使用Array Set/Get方法时获取错误类型不匹配 import Html exposing (beginnerProgram, div, button, text, p, Html, span) import Html.Events exposing (onClick) import Array main = beginnerProgram { model = [0,7],
React
,Redux
,ES6
需要帮助,使用数组
而不是列表
优化下面的反例。
尝试使用Array Set/Get
方法时获取错误类型不匹配
import Html exposing (beginnerProgram, div, button, text, p, Html, span)
import Html.Events exposing (onClick)
import Array
main =
beginnerProgram { model = [0,7], view = view, update = update }
view model =
div []
[ div [] [ button [ onClick AddCounter ] [ text "Add Counter" ] ]
, div [] (List.indexedMap (\index data -> (viewCounter index data)) model)
]
viewCounter: Int -> Int -> Html Msg
viewCounter index data =
div [] [
p [] [text ("Counter " ++ toString index )]
, button [ onClick (Decrement index) ] [ text "-" ]
, span [] [ text (toString data) ]
, button [ onClick (Increment index) ] [ text "+" ]
]
type Msg =
AddCounter
| Increment Int
| Decrement Int
incrementSelectedIndex index selectedIndex data =
if index == selectedIndex then data + 1
else data
decrementSelectedIndex index selectedIndex data =
if index == selectedIndex then data + 1
else data
update msg model =
case msg of
AddCounter ->
List.append model [0]
Increment selectedIndex ->
(List.indexedMap (\index data ->
(incrementSelectedIndex index selectedIndex data)) model)
Decrement selectedIndex ->
(List.indexedMap (\index data ->
(decrementSelectedIndex index selectedIndex data)) model)
Array.get
返回一个可能是一个
,因为可能找不到请求的索引。这可能与您使用过的其他语言不同,这些语言在索引超出范围时往往会抛出异常
在Elm中,Maybe
类型有两个可能的值:Nothing
,和Just a
,其中a
是您关心的实际值
您可以使用case
语句来区分这两个选项。下面是使用数组的获取
和设置
函数的增量
案例的示例:
Increment selectedIndex->
case Array.get selectedIndex的模型
只需val->Array.set selectedIndex(val+1)模型
无->模型
请注意,如果我们请求一个不存在的索引,我们将得到
Nothing
,只返回原始数组,而不是使程序崩溃。数组。get
返回一个可能是一个,因为可能找不到请求的索引。这可能与您使用过的其他语言不同,这些语言在索引超出范围时往往会抛出异常
在Elm中,Maybe
类型有两个可能的值:Nothing
,和Just a
,其中a
是您关心的实际值
您可以使用case
语句来区分这两个选项。下面是使用数组的获取
和设置
函数的增量
案例的示例:
Increment selectedIndex->
case Array.get selectedIndex的模型
只需val->Array.set selectedIndex(val+1)模型
无->模型
请注意,如果我们要求一个不存在的索引,我们将得到Nothing
,只返回原始数组,而不是使程序崩溃。最后我明白了,可能不费吹灰之力,非常感谢Chad。对于此类用例,是否有推荐的使用数组或列表的方法,请澄清w.r.t对性能(内存和速度)的影响。还有更多的信息以及我最终理解的链接,可能不费吹灰之力,非常感谢Chad。对于此类用例,是否有推荐的使用数组或列表的方法,请澄清w.r.t到性能(内存和速度)。还有更多的信息和链接