Haskell List Concatenation vs. Format (head: tail)

I always wrote my recursive functions that produce a list in this format:

recursiveFunc :: [a] -> [b] recursiveFunc (x:xs) = [change x] ++ resursiveFunc xs where change :: a -> b change x = ... 

I understand that any function like the one above can be written for the case a -> b , and then just map ed over the set [a] , but please take this situation with irrigation as an example.

HLint suggests replacing [change x] ++ recursiveFunc xs with change x : recursiveFunc xs .

Is this proposal purely aesthetic, or is there any influence on how Haskell performs this function?

+6
source share
3 answers

When using [change x] ++ recursiveFunc xs you create an extra singleton list, which is then separated by the ++ function. Using : this will not happen.

Plus ++ is a function that will then use the constructor : When you use : directly, there is no need to call a function.

Thus, use : more efficient in theory (the compiler can, however, optimize these differences).

+9
source

The main advantage is that change x : blah is clearer - (:) - this is exactly what you are trying to do (add one item to the list). Why call two functions when you do?

The proposed method is also a little more efficient - your path creates a list of 1 element and then discards it and replaces it with another list of links. Another way is simply to create a link to one list. However, the difference is small enough to be unimportant in 99% of cases.

+4
source

Line

 recursiveFunc (x:xs) = [change x] ++ resursiveFunc xs 

a bit confusing as it is not in normal form. This means that ++ can be replaced right away with one right-hand side of its definition:

 (++) (a:as) bs = a:((++) as bs) (++) [] bs = bs -- => recursiveFunc (x:xs) = (change x):((++) [] resursiveFunc xs) -- => recursiveFunc (x:xs) = (change x):(resursiveFunc xs) 

The Haskell compiler automatically applies such a conversion.

But since it is so trivial, it makes your code more difficult to read. One looks at him and asks "wait ... what?"

+4
source

Source: https://habr.com/ru/post/909756/


All Articles