在Haskell中旋转一个列表 [英] Rotate a list in Haskell
本文介绍了在Haskell中旋转一个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个定义 a
的定义,
I have a list a
defined,
let a = ["#","@","#","#"]
如何旋转 @
两个空格,以便它像这样结束?
How can I rotate the @
two spaces, so that it ends up like this?
["#","#","#","@"]
工作,
I thought this might work,
map last init a
但是语法可能不同,因为map只能用于一个函数?
but maybe the syntax has to be different, because map can only work with one function?
推荐答案
为了完整起见,一个兼容空列表和无限列表的版本。
For completeness's sake, a version that works with both empty and infinite lists.
rotate :: Int -> [a] -> [a]
rotate _ [] = []
rotate n xs = zipWith const (drop n (cycle xs)) xs
然后
Then
Prelude> rotate 2 [1..5]
[3,4,5,1,2]
这篇关于在Haskell中旋转一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文