'Attempting to create an Insert for Haskell that inserts at a certain point in a list

as the title suggests, I am attempting to create a Haskell function that can insert at a certain point in a list, and if the point I try to insert into is larger than the size of the list, no insertion is done. This is my first time using Haskell and I have only just begun learning the language, so it's likely I am missing something simple.

Now, as an example of what I mean, here are examples of inputs and their expected outputs

\> insert 3 100 [1,2,3,4,5,6,7,8] 
[1,2,3,100,4,5,6,7,8] 

\> insert 8 100 [1,2,3,4,5,6,7,8]  
[1,2,3,4,5,6,7,8,100] 

\> insert 9 100 [1,2,3,4,5,6,7,8] 
[1,2,3,4,5,6,7,8] 

\> insert 3 100 [] 
[] 

Here is the code I have attempted thus far

insert 0 y [] = [y]
insert n y [] = []
insert 0 y [x:xs] = y:x:[xs]
insert n y [x:xs] = y:(insert (n-1) y [x:xs])

This code produces the following error in insert 0 y [x:xs] = y:x:[xs] at the second xs

Image

Image Transcript:

xs :: [a_aEmT]
Defined at C:\Users\darin\OneDrive\Desktop\Haskell\Lab1_Submit.hs:16:15
_ :: a_aEmT[sk:1]
• Couldn't match expected type ‘a’ with actual type ‘[    
  ‘a’ is a rigid type variable bound by the inferred type of insert :: t -> a -> [[a]] -> [a] at C:\Users\darin\OneDrive\Desktop\Haskell\Lab1_Submit.hs:(14,1)-(17,45)
• In the expression: xs
  In the second argument of ‘(:)’, namely ‘[xs]’
  In the second argument of ‘(:)’, namely ‘x : [xs]’
• Relevant bindings include
xs :: [a]

I thank you in advance for any help you can give. I assume this is a rather trivial problem, and I just lack the understanding to solve it.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source