Use haskell for above problem, make sure it compiles and work perfectly! Write t
ID: 3833123 • Letter: U
Question
Use haskell for above problem, make sure it compiles and work perfectly!
Write the function insertAt:: Int rightarrow a rightarrow [a] rightarrow [a]. insert At n x xs will insert the element x into the list xs at position n items from the beginning of xs. In other words, skip n items in xs, then insert the new element. You can assume that n will be a non-negative number. If n is greater than the length of the list rs then add it to the end of the list. For example insert At 3 '-' "abcde" rightarrow "abc-de" insert At 2 100 [1. 5] rightarrow [1, 2, 100, 3, 4, 5]Explanation / Answer
Since you want to add the element x at nth position, you can just use following code.
In the following code I used fold version. The advantage of that is,
Compared to the simple recursive definition, the fold version visits every elements of the list, whereas we could just stop after insertion of the element.
insertAt :: a -> [a] -> Int -> [a]
insertAt elt lst pos = foldr concat' [] $ zip [1..] lst
where
concat' (i, x) xs
| i == pos = elt:x:xs
| otherwise = x:xs
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.