I’m reading through Learn You a Haskell and reached a spot where I’m trying to move an element in a list to the head. I’ve come up with what I think is the naive way and I’m curious if someone can show me what the experienced Haskell programmer would do instead.
In this example, I have a list of Integers and I want to move the element ‘4’, which would be index ‘3’, to the head of the list.
let nums = [1, 2, 3, 4, 5]
(nums !! 3) : delete (nums !! 3) nums
returns [4, 1, 2, 3, 5].
What do you think?
I would do it this way:
splitAtsplits a list at the given position, it returns the two parts that are created by the splitting (herehsandts). The element that should be moved to the front is now at the beginning ofts.head tsreturns just this first element ofts,tail tsreturns everything but that first element. The result of the function are just these parts combined in the right order:hsconcatenated withtail tsand prepended by the elementhead ts.