Haskell是否有列表切片(即Python)? [英] Does Haskell have List Slices (i.e. Python)?

查看:401
本文介绍了Haskell是否有列表切片(即Python)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Haskell对 Python列表切片有类似的语法糖吗?



例如在Python中:

  x = ['a','b', 'c','d'] 
x [1:3]

索引1包含索引2(或索引3除外):

  ['b','c'] 

我知道Haskell的(!!)函数特定的索引,但有没有一个等效的切片或列表范围函数?

解决方案

没有内置函数来切片列表,但您可以使用 drop take 自己轻松编写一个:

 切片从xs = take(to  -  from + 1)(从xs中删除)

应该指出的是,由于Haskell列表是单向链表(当python ts是数组),像这样创建子列表将是 O(to),而不是 O(1) (当然假设整个列表实际上被评估 - 否则Haskell的懒惰会生效)。

Does Haskell have similar syntactic sugar to Python List Slices?

For instance in Python:

x = ['a','b','c','d']
x[1:3] 

gives the characters from index 1 to index 2 included (or to index 3 excluded):

['b','c']

I know Haskell has the (!!) function for specific indices, but is there an equivalent "slicing" or list range function?

解决方案

There's no built-in function to slice a list, but you can easily write one yourself using drop and take:

slice from to xs = take (to - from + 1) (drop from xs)

It should be pointed out that since Haskell lists are singly linked lists (while python lists are arrays), creating sublists like that will be O(to), not O(1) like in python (assuming of course that the whole list actually gets evaluated - otherwise Haskell's laziness takes effect).

这篇关于Haskell是否有列表切片(即Python)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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