Can a list head ever represent more than one value

If I call a function interleave(defined below - this is a function to insert a number (or any type) at each position of the list), like this, the resulting lists are the same length

interleave 1 [2,3,4]
[[1,2,3,4],[2,1,3,4],[2,3,1,4],[2,3,4,1]]

However, I expected the lengths of the lists to be shorter, because a recursive call interleavepasses the list minus the head (i.e. only ys). As the tail of the list gets shorter with each call, I expect the resulting lists to be shorter.

interleave :: a -> [a] -> [[a]]
interleave x []     = [[x]]
interleave x (y:ys) = (x:y:ys) : map (y:) (interleave x ys)

How do lists end up being the same length if the list argument for the recursive call gets shorter?

The only answer I can imagine is that the displayed value map (y:)is more than one digit in recursive calls (i.e. 2 in [2,1,3,4] and 2,3in [2, 3,1, 4] and 2,3,4in [2,3,4,1] `, but I'm not sure if this is possible, and I don’t know how to write values ​​at runtime in haskell.

A question, in other words, can y(the head of a list) represent more than one value in recursive calls?

Responding to the question (if relevant), please confirm / explain, if (x:y:ys)in the (x:y:ys) : map (y:) (interleave x ys)only ever represents one list (ie, it is [1,2,3,4-introduced an integer argument in the first position).

(This can help if you can show the func function order or how the values ​​will be stored on the stack)

+4
1

; . . :

interleave 1 []
= { first clause of definition }
[[1]]

, , . , map (y:), , , .

interleave 1 [4]
= { list syntax }
interleave 1 (4:[])
= { second clause of definition }
(1:4:[]) : map (4:) (interleave 1 [])
= { recursive call, which produces short answers }
(1:4:[]) : map (4:) [[1]]
= { definition of map, which lengthens each answer }
(1:4:[]) : [4:[1]]
= { list syntax }
[[1,4],[4,1]]

interleave 1 [3,4] interleave 1 [4] [[1,4],[4,1]], map (3:) [[3,1,4],[3,4,1]].

:

, ?

, , - , interleave n - n+1.

can y ( ) ?

, . , - .

/, (x:y:ys) (x:y:ys) : map (y:) (interleave x ys) - (.. [1,2,3,4- , ).

.

+4

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


All Articles