So I've came across this function definition that takes a list (xs) and splits it into three parts as an output.
The thing is I'm having difficulty understanding it. I understand the first part which takes n of the list (xs) where n is defined as dividing the length of the list (xs) by 3. But after that I'm not sure entirly sure whats going on.
If anyone could walk me through this function that would be great.
Here is the code:
--SPLITS A LIST INTO THREE PARTS---------------------------------------------------------
split3 xs = (take n xs , take n (drop n xs) , drop (n*2) xs)
where n = length xs `div` 3
The second part drops the first n
elements and takes the following n
elements.
[------- n -------][------- n -------][------- n -------]
^ ^
dropped taken by `take` ^ dropped by `take`
A concrete example could be a list of [1,2,3]
, n == 1
.
take n (drop n xs)
== take 1 (drop 1 [1,2,3])
== take 1 [2,3]
== 2
The third part drops twice n
and takes the rest
[---- 2n -----][---- n -----]
^ ^
dropped taken by `drop`