在haskell中反转列表 [英] Reverse a list in haskell
问题描述
以下是我的代码:
reverseList :: [Int] - > [Int]
reverseList [] = []
reverseList(x:xs)= x:reverseList xs
最终发生的事情是我最终以相同的顺序返回列表。我甚至有一个解决方案来解决这个问题,但我想知道我在这里做错了什么?我对哈斯克尔很新,所以我认为我应该更多地关注于理解,然后我可以轻松地解决更多的问题。我知道这个问题有很多解决方案,但是我需要更多的帮助来理解esp在这段代码中做错了什么。
您将列表分隔为头部和尾部,但随后按照相同的顺序重新组装列表。以 [1,2,3]
为例:
在第一次调用中, x
将是 1
,并且 xs
将会是 [2,3]
。然后你创建一个新的列表,在前面包含 x
(so 1),后面跟着 reverseList [2,3
。
I am trying to reverse a list.
Following is my code:
reverseList :: [Int] -> [Int]
reverseList [] = []
reverseList (x:xs) = x:reverseList xs
What ends up happening is I end up getting the list back in same order. I even have a solution for how to reverse the list but I am trying to understand what I did wrong here ? I am very new to haskell so think I should focus on understanding more then I can solve more problems with ease. I know there are many solutions out there for this problem but I need more help in the understanding esp what I did wrong here in this code.
You are separating the list into head and tail, but then re-assemble the list in the same order. Take the list [1, 2, 3]
for example:
In the first call, x
will be 1
, and xs
will be [2, 3]
. Then you create a new list, consisting of x
(so 1) at the front, followed by reverseList [2, 3
.
这篇关于在haskell中反转列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!