如何在Haskell中向右或向左移动列表的1个元素? [英] How to move 1 element of a List to right or left in Haskell?

查看:79
本文介绍了如何在Haskell中向右或向左移动列表的1个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找答案,但找不到答案.可以说,我们有一个像[1,10,4,5,3]的列表,我该如何向左移动5以便该列表变成[1,10,5,4,3].

Hi I have been looking for an answer but could not find one. Lets say that we have a list like [1,10,4,5,3] how can I shift 5 to left so that this list becomes [1,10,5,4,3].

我试图通过找到该元素的索引来进行swapElementsAt,但是它看起来非常不足.

I tried to swapElementsAt by finding the index of that element but it looks very insufficient.

推荐答案

考虑一下,如果您要从输入列表的左端到右端查看列表开头的非常局部的附近(从这就是您可以轻松进行模式匹配的方式.

Consider how would you write this function if you were to traverse the input list from left to right looking at a very local vicinity of the beginning of the list (since that's what you can easily pattern-match on).

最直接的方法是在前两个元素上进行模式匹配,并检查第二个元素是否与您的模式匹配.如果是这样,只需通过交换这些元素并追加列表的其余部分来构建新列表,否则,递归地遍历其余部分.

The most straightforward way would be to pattern-match on the first two elements, and check if the second element matches your pattern. If so, just build a new list by swapping these elements and appending the remainder of the list, otherwise, go recursively over the rest.

在代码中:

swapElem :: Eq a => a -> [a] -> [a]
swapElem e (x:y:xs) | y == e = y : x : xs
swapElem e (x:xs) = x : swapElem e xs
swapElem _ [] = []

仅当列表中至少有两个元素时,第一个模式才匹配,而第二个元素等于所需的元素.如果元素较少或第二个元素不是正确的元素,它将落入第二个模式,该模式与任意非空列表匹配,并在列表的其余部分调用swapElem.第三种模式是提供空输入列表的基本递归情况.

The first pattern only matches when there are at least two elements in the list, and the second element is equal to the desired one. If there are less elements or the second element is not the right one, it will fall through to the second pattern, that matches arbitrary non-empty list and calls swapElem on the remainder of the list. The third pattern is there to provide the base recursion case of an empty input list.

请注意,此代码仅更改目标元素的首次出现:

Note this code only changes the first occurrence of the target element:

Prelude> swapElem 5 [1, 10, 4, 5, 3]
[1,10,5,4,3]
Prelude> swapElem 5 [1, 10, 5, 4, 5, 3]
[1,5,10,4,5,3]

您将如何更改它以便将所有5左移?

How would you change it so that it left-shifts all 5s?

此外,答案取决于您输入的内容是什么. @Scarabyte的答案考虑了为您提供目标元素的位置的情况,而这种方法反而考虑了您想向左移动的元素.

Also, the answer depends on what exactly is your input. The answer by @Scarabyte considers the case where you're given the position of the target element, while this approach instead considers the element that you want to shift left.

这篇关于如何在Haskell中向右或向左移动列表的1个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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