Home > Software engineering >  Swap the second list parameter's first element with the the first list parameter's first e
Swap the second list parameter's first element with the the first list parameter's first e

Time:10-09

Implement the

replaceHead :: [a] -> [a] -> [a]

function, that works as the title says. For example:

replaceHead "okay" "mom" == "mkay"

or:

replaceHead [0,2,3] [1,20,30] == [1,2,3]

I tried using

replaceHead a b = [head b, a]

which doesn't compile. I don't have any more ideas as to how I can take b's first element, swap it with a's first element, and then return that list. Can you help? Thanks for you answers in advance!

CodePudding user response:

The problem is that a is a list of items, whereas head b is an item. You can thus not use [head b, a] since then the first item is for example an Int, whereas a is an [Int]. In order to meet the sample output, we furthermore need to work with the tail of the first list, not the entire first list.

You can however prepend the tail a list by using the (:) :: a -> [a] -> [a] data constructor:

replaceHead :: [a] -> [a] -> [a]
replaceHead a b = head b : tail a

It might be better to work with pattern matching here, and implement this as:

replaceHead :: [a] -> [a] -> [a]
replaceHead (_:as) (b:_) = b : as

In that case you probably should define a case when the first and/or second list is empty:

replaceHead :: [a] -> [a] -> [a]
replaceHead (_:as) (b:_) = b : as
replaceHead [] [] = …
replaceHead [] (b:bs) = …
replaceHead (a:as) [] = …
  • Related