如何通过elm中的索引获取列表项?

问题描述 投票:23回答:3

我有一个清单,现在我想要第n项。在Haskell中我会使用!!,但我找不到榆树的变种。

list elm
3个回答
14
投票

在榆树中没有相同的东西。你当然可以自己实现它。

(注意:这不是“总”函数,因此当索引超出范围时会创建异常)。

infixl 9 !!
(!!) : [a] -> Int -> a
xs !! n  = head (drop n xs)

更好的方法是使用Maybe数据类型定义一个总函数。

infixl 9 !!
(!!) : [a] -> Int -> Maybe a
xs !! n  = 
  if | n < 0     -> Nothing
     | otherwise -> case (xs,n) of
         ([],_)    -> Nothing
         (x::xs,0) -> Just x
         (_::xs,n) -> xs !! (n-1)

32
投票

Elm在0.12.1中添加了数组,并且在0.19中对实现进行了大规模的大修,以提高正确性和性能。

import Array

myArray = Array.fromList [1..5]

myItem = Array.get 2 myArray

数组是零索引的。目前不支持负指数(我知道这很糟糕)。

请注意myItem : Maybe Int。 Elm尽其所能避免运行时错误,因此out of bounds access返回一个明确的Nothing

如果你发现自己想要索引列表而不是头部和尾部,你应该考虑使用数组。

Array documentation


1
投票

我用过这个:

(!!): Int -> List a -> Maybe a

(!!) index list =                          -- 3 [ 1, 2, 3, 4, 5, 6 ]

   if  (List.length list) >= index then

        List.take index list               -- [ 1, 2, 3 ]
        |> List.reverse                    -- [ 3, 2, 1 ]
        |> List.head                       -- Just 3
   else 
      Nothing

当然你得到一个Maybe,你需要在使用这个功能时解开它。不能保证你的列表不会是空的,或者你要求一个不可能的索引(如1000) - 这就是为什么elm编译器会强迫你考虑这种情况。

main = 
let 
  fifthElement = 
    case 5 !! [1,2,3,4,255,6] of  // not sure how would you use it in Haskell?! But look's nice as infix function. (inspired by @Daniël Heres)
      Just a ->
        a
      Nothing ->
        -1
in
    div [] 
        [ text <| toString fifthElement ]         // 255
© www.soinside.com 2019 - 2024. All rights reserved.