Array.indexedMap类型不匹配

时间:2018-08-26 17:23:43

标签: elm

这是我上Elm的第一天,但​​我无法处理这个打字问题。我尝试在应用中使用Array来使用indexedMap,但是当我将自定义函数作为第一个参数应用时,编译器会抱怨类型不匹配,这对我来说似乎不正确。我在这里想念什么?

main =
  let
    values = Array.fromList [0, 1, 2, 3, 4, 5]
  in
    Array.indexedMap
      (addIndex values) /* <-- It tells me that it wants "Int -> b", but I would give it "Int -> Int" */
      values
    /* Should be [0, 2, 4, 6, 8, 10] */

addIndex values =
  \index ->
    let
      x = Maybe.withDefault 0 (Array.get index values)
    in
      x + index

1 个答案:

答案 0 :(得分:7)

为了使您的代码编译,您需要更改addIndex函数,因为Array.indexedMap期望的值类型为Int -> a -> b,但是addIndex返回的类型值Int -> b

addIndex values =
  \index a ->
    let
      x = Maybe.withDefault 0 (Array.get index values)
    in
      x + index

这里是其中的illustration

无论如何,您可能想知道,这另一个论点是干什么的?实际上,它是与索引关联的数组的迭代值。这意味着,您不需要此行:

x = Maybe.withDefault 0 (Array.get index values)

因为您已经在迭代中具有此值。因此,代码可以简化为:

main =
  let
    values = Array.fromList [0, 1, 2, 3, 4, 5]
  in
    text (Debug.toString (Array.indexedMap addIndex values))

addIndex : Int -> Int -> Int
addIndex index x = x + index