Duplicate each item in a Haskell list

by functions How can I duplicate each element of the list with myself twice. for example duplicate [1,3,5]should return [1,1,3,3,5,5]?

and replace the item with some other item in the list. for example replace 3 30 [1, 3 ,4 ,5, 3, 4]should return[1, 30, 4, 5, 30, 4]

I am brand new at Haskell and today I have to submit my homework.

Any help would be greatly appreciated!

+2
source share
4 answers
duplicateEach  = (>>= replicate 2)
duplicateEach2 = concatMap (replicate 2)
duplicateEach3 xs = [ y | x <- xs, y<-[x,x] ]

import Data.List.Split

replaceOne f t xs = [ y | x<-xs, let y = if x==f then t else x]

replaceSublist f t = intercalate t . sepBy f   -- f and t is lists
+9
source

Match the elements and copy them. Then compare the results:

concatMap (replicate 2) [1,3,5]

In the second issue, consider Data.List.Utils

replace [3] [30] [1,3,4,5,3,4]
+10
source

:

duplicate_each xs = foldr dup [] xs
    where dup x y = x : x : y

, .

+3

:

.

xs, , x [x, x] ; , . - :

k :: a -> [a]
k x = [x,x]

g :: (a -> b) -> [a] -> [b]
g f [] = []
g f (x:xs) = f x : g f xs

duplicate :: [a] -> [a]
duplicate = concat . (g k)

g = map concat . g = concatMap, , , :

duplicate :: [a] -> [a]
duplicate =  concatMap (\x -> [x,x])
          => concatMap (replicate 2)

a b, , b a:

f :: Eq a => a -> a -> a -> a
f o r x = if x == o then r else x

replaceOn :: Eq a => a -> a -> [a] -> [a]
replaceOn o r [] = []
replaceOn o r (x:xs) = f o r x : h o r xs

h = map f, :

replaceOn :: a -> a -> [a] -> [a]
replaceOn o r = map (\x -> if x == o then r else x)

I am not an Haskell expert. However, this helps me break down Haskell's problems into sequences of "return values". It is like “steps” in an imperative language. The steps are composed using combinators, higher order functions, and ordering functions. You can think of a sequence, for example: do f to get x; on g with fx to get x ', etc.

+2
source

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


All Articles