J.Bauman
J.Bauman

Reputation: 79

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.

Upvotes: 1

Views: 98

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477160

[x:xs] is a pattern for a singleton list that has a non-empty list (x:xs). This will thus match for [[1,4,2]] for example where x is 1 and xs is [4,2]. But not for a non-empty list itself: that is (x:xs). Furthermore it also means that if you x is an element of a list of list, hence the type errors if you want to use y : x : [xs].

There are also some other mistakes: it is y : x : xs instead of y : x : [xs] since xs is already a list [a] of items, and in caseof recursion, you yield x, not y, so:

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

You can simplify this to:

insert :: Int -> a -> [a]
insert 0 y xs = y : xs
insert n y (x:xs) = x : insert (n-1) y xs
insert _ _ [] = []

Upvotes: 2

Related Questions