Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a lists of lists with new element in each position

i'm new in the haskell world and i'd like to know how to insert a value in each position of a list in haskell, and return a lists of sublists containing the value in each position. For example:

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]]
like image 275
john Avatar asked Jan 30 '23 16:01

john


1 Answers

insert' :: a -> [a] -> [[a]]
insert' y [] = [[y]]
insert' y xss@(x:xs) = (y : xss) : map (x :) (insert' y xs)

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

  1. y appears in front of x. Then we can just use y : xss.
  2. y appears somewhere after x. We therefore just insert it in the rest of our list and make sure that x is the first element with map (x:).
like image 123
delta Avatar answered Feb 01 '23 06:02

delta