Reverse a list in haskell

后端 未结 5 795
野的像风
野的像风 2020-12-14 19:06

I am trying to reverse a list.

Following is my code:

reverseList :: [Int] -> [Int]
reverseList [] = []
reverseList (x:xs) =  x:reverseList xs
         


        
5条回答
  •  情深已故
    2020-12-14 20:00

    There are several ways to solve this problem in Haskell. The naive approach would be to use the concatenate function ++:

    reverseList [] = []
    reverseList (x:xs) = reverseList xs ++ [x]
    

    However, this will be really slow for large lists since Haskell lists are really singly linked lists, so in order to append an element you have to traverse the entire list. An alternative would be to keep up with the list you're building in a helper function:

    reverseList = go []
        where
            go acc [] = acc
            go acc (x:xs) = go (x:acc) xs
    

    However, this is really just the fold pattern:

    reverseList = foldl (\acc x -> x : acc) []
    

    But \acc x -> x : acc is just flip (:), so this can be written as

    reverseList = foldl (flip (:)) []
    

    However, the easiest way would probably be to just use the reverse function in Prelude.

    I would like to point out that your type of reverseList :: [Int] -> [Int] could be generalized to :: [a] -> [a], you don't do anything special with the elements of the list, you're just building a new list with them.

提交回复
热议问题