如何在Elm中按索引获取列表项? [英] How do I get a list item by index in elm?

查看:82
本文介绍了如何在Elm中按索引获取列表项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个清单,现在我要第n个清单.在Haskell中,我将使用!!,但找不到该榆木的变体.

I got a list, and now I want the nth item. In Haskell I would use !!, but I can't find an elm variant of that.

推荐答案

榆木中没有与此等效的解决方案. 您当然可以自己实施.

There is no equivalent of this in Elm. You could of course implement it yourself.

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

(Note: This is not a "total" function, so it creates an exception when the index is out of range).

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

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

A better way would be to define a total function, using the Maybe data type.

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)

这篇关于如何在Elm中按索引获取列表项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆