I am new to Haskell. I am trying to write a function that, given the list l, element x that exists in the list, and an element to insert y: insert element y before the first occurrence of the element x, in list l. If element x does not exist in the list, then leave the list unchanged.
I am having a lot of trouble with this one and would appreciate any suggestions.
This is what I tried (‘n’ is the first occurrence of element x):
insertSpecial :: Eq a => a -> a -> [a] -> [a]
insertSpecial let (ys,zs) = splitAt n xs in ys ++ [y] ++ zs
How about
This approach uses a general method known as recursion. This means that the task at hand is broken down into one or several base case(s), for which the result can be defined easily, and a general case which can be solved by breaking down the work into parts. In the general case the function is then called recursively on the smaller task. The goal is to eventually end up in a base case at which point the work is done. See also this part from Learn you a Haskell.
For
insertSpecialwe can define two base cases:If the list is empty it doesn’t contain the element we’re looking for and we want to leave the list unchanged in this case, so we simply return an empty list. We’re done.
If the list is not empty and the first element is the one we are looking for we stick
yin front of this list and return that. Again we’re done.That leaves us with the case where the list is not empty but the first element is not the one we are looking for. In this case we break up the work (the list) in two parts: the first element and the rest of the elements. We put the first element in front of the list that is returned by calling
insertSpecialon the rest of the list. This is where the recursion happens: a call ofinsertSpecialcalls itself.One thing that is maybe a little difficult to understand about this is how the last case produces a list that only differs from the original list by inserting an element at the right place. Let’s consider an example. Say we have the list
Note that in Haskell, regular strings are just lists of characters so
['h','e','l','o'] == "helo". Also note that['h','e','l','o']is really syntactic sugar for'h':'e':'l':'o':[]. (:takes an element and a list and prepends that element to the list. it is also called cons).Now let’s insert the missing
'l'in front of the'o':Since
"helo"is not empty'h'is bound toaand"elo"is bound toas(furthermore,'o'is bound toxand'l'is bound to'y'). Sincea == 'h' /= 'o' == xwe are in the third case, soNow with
insertSpecial 'o' 'l' "elo"we again fall into the third case ("elo"is not empty and'o' /= 'e'):Which again leads to the third case:
Now in the last call we’re actually binding
'o'toawhich is equal toxand we land in the second case, where we prepend the value ofy('l') toa('o') andas([]), so we get:Putting all these substitutions together we get:
And as described above
'h' : 'e' : 'l' : 'l' : 'o' : [] == ['h','e','l','l','o'] == "hello". Yay.