Andrew Nodermann
Andrew Nodermann

Reputation: 690

Head to end of list and back and move elem to index

I have list of strings

["1", "2", "3", "4", "5"]

I wrote a first function, but it doesn't work

head_to_end :: [String] -> [String]
head_to_end x = t : h
    where h = `head` x
          t = `tail` x

I should get something like this

head_to_end ["1", "2", "3", "4", "5"] -> ["2", "3", "4", "5", "1"]
last_to_head ["1", "2", "3", "4", "5"] -> ["5", "1", "2", "3", "4"]

move_elem_1_to_4 :: Int -> Int -> [String] -> [String]
move_elem_1_to_4 ["a", "b", "c", "d", "e"] -> ["b", "c", "d", "a", "e"]

Upvotes: 1

Views: 2482

Answers (2)

James
James

Reputation: 4737

You can use pattern matching to access the head and tail of the list separately, then append the head (as a singleton list) to the end of the tail of the list using the ++ operator.

headToEnd :: [a] -> [a]
headToEnd []     = []
headToEnd (x:xs) = xs ++ [x]

To move the last element of the list to the beginning, we can not use pattern matching, but we can use the last and init functions (imported with Prelude by default) in the Data.List module (from the base library) to access these values. This is where you would use the cons operator, (:), to construct the new list with the values from last and init.

lastToHead :: [a] -> [a]
lastToHead [] = []
lastToHead xs = last xs : init xs

Look up the types of each operator (:) and (++) in GHCI. It makes it very clear why your examples do not work.

λ :t (++)
(++) :: [a] -> [a] -> [a]
λ :t (:)
(:) :: a -> [a] -> [a]

Here's the reference on Data.List for info on the functions and operators I just mentioned. I found this page myself by visiting Hoogle, then searching for "Data.List", then clicked on "base Data.List" which was the first result.

Upvotes: 1

jamshidh
jamshidh

Reputation: 12070

Instead of (:), you need to move the head to the end using (++)

head_to_end x = tail x ++ [head x]

Remember, (:) is of type a->[a]->[a].... You would need a single element on the left side, and a list on the right. Your types were the reverse.

Also note that moving the head to the tail of a list like this is an expensive operation, the code will have to rebuild the full list.

Upvotes: 2

Related Questions