How to move an item in a list in Haskell?

I read through Teach you Haskell and got to the place where I am trying to move an item to a list in the head. I came up with what I think is naive, and I'm curious if anyone can show me what an experienced Haskell programmer did instead.

In this example, I have a list of integers, and I want to move the element "4", which will be the 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?

+6
list haskell
source share
5 answers

I would do it like this:

 move n as = head ts : (hs ++ tail ts) where (hs, ts) = splitAt n as 

splitAt splits the list at this position, it returns the two parts that are created by splitting (here hs and ts ). The element that should be moved to the front is now at the beginning of ts . head ts returns only this first element ts , tail ts returns everything except the first element. The result of the function is only these parts, combined in the correct order: hs , linked to tail ts and added by the head ts element.

+15
source share

Experienced Haskellers almost never use list indexing. I would use break to avoid repeated crawls (assuming you want to map element "4" and not index "3"):

 case break (== 4) [1, 2, 3, 4, 5] of (a,x:xs) -> x:a ++ xs (a,xs) -> a ++ xs 

How in:

 Prelude Data.List> case break (== 4) [1, 2, 3, 4, 5] of (a,x:xs) -> x:a ++ xs; (a,xs) -> a ++ xs [4,1,2,3,5] 

We can do the same with indexing via 'splitAt':

 Prelude Data.List> case splitAt 3 [1, 2, 3, 4, 5] of (a,x:xs) -> x:a ++ xs; (a,xs) -> a ++ xs [4,1,2,3,5] 
+11
source share

slight modification on sth solution:

 toHead n xs = x : pre ++ post where (pre, x:post) = splitAt n xs 

using pattern matching instead of head n tail

+8
source share

There also

 toHead nl = l !! n : take nl ++ drop (n+1) l 

which might be a little easier than using splitAt .

+3
source share

What is joint disease?
I read the same a few days ago. Looked up and wrote it as shown below.

 nums !! 3 : [x | x <- nums, (x == (num !! 3)) == False] 
0
source share

All Articles