Creating lists of lists with a new item at each position

I am new to the haskell world, and I would like to know how to embed a value in each position of a list in haskell, and return lists of sublists containing a value in each position. For instance:

insert' :: a -> [a] -> [[a]]
insert' a [] = [[a]]
insert' a list = ??

To get something like:

insert' 7 [1,2,3] = [[7,1,2,3],[1,7,2,3],[1,2,7,3],[1,2,3,7]]
+4
source share
3 answers
insert' :: a -> [a] -> [[a]]
insert' y [] = [[y]]
insert' y xss@(x:xs) = (y : xss) : map (x :) (insert' y xs)

While the case with the empty list becomes natural, take a look at insert' y xss@(x:xs). We essentially have two cases that we need to cover:

  • yappears before x. Then we can just use y : xss.
  • y - x. , x - map (x:).
+8

@delta answer , . x ys = [y1,y2,...,yn], , , x : ys.

. [y1,x,y2,...,yn]. y1 : x : y2s. y1 : ....

: , , . : id. id (x:ys), , , (x:ys).

, id, id2 = \z -> id (y1:z). , , y1 , , id2 . id3 = \z -> id2 (y2:z). y1 y2 , z.

, :

insert' :: a -> [a] -> [[a]]
insert' x = go id
    where go d [] = [d [x]]
          go d ys@(yh:yt) = (d (x : ys)) : go (d . (yh :)) yt

, insert' go, - id. , . , basecase: [x] ( ) , , , x .

, d (x : ys): x d. d y1 : y2 : ... : yk , x. , go (d . (yh :)) yt : , (yh :) . , : yh.

:

*Main> insert' 4 []
[[4]]
*Main> insert' 4 [1,2,5]
[[4,1,2,5],[1,4,2,5],[1,2,4,5],[1,2,5,4]]
*Main> insert' 7 [1,2,3]
[[7,1,2,3],[1,7,2,3],[1,2,7,3],[1,2,3,7]]
0

:

import Data.List

spread :: a -> [a] -> [[a]]
spread x xs = zipWith (++) (inits xs) ((x:) <$> tails xs)

*Main> spread 7 [1,2,3]
[[7,1,2,3],[1,7,2,3],[1,2,7,3],[1,2,3,7]]
*Main> spread 7 []
[[7]]

, .

  • (x:) <$> tails xs - (x:) tails xs. , tails [1,2,3] [[1,2,3],[2,3],[3],[]], fmap, <$> . zipWith.
  • (inits xs), [[],[1],[1,2],[1,2,3]], zipWith.
  • zipWith (++), , .

Thus, we can also express the same functionality with functionals of the applicative function as follows:

spread :: a -> [a] -> [[a]]
spread x = zipWith (++) <$> inits <*> fmap (x:) . tails

In this case, a fmapfunction zipWith (++)with type [[a]] -> [[a]] -> [[a]]over inits, and then apply it to fmap (x:) . tails.

It may get more meaning, but it becomes more difficult to read (at least for me). In my opinion, this is as good as it gets.

0
source

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


All Articles