haskell split a list at position n
To split a Haskell list at a specific position, you can use the splitAt
function. This function takes an index n
and a list xs
as arguments and returns a tuple containing two lists. The first list contains the elements of xs
up to index n
, and the second list contains the elements of xs
starting from index n
.
Here's an example of how you can use the splitAt
function:
splitList :: Int -> [a] -> ([a], [a])
splitList n xs = splitAt n xs
In this example, the splitList
function takes an integer n
and a list xs
as input and calls the splitAt
function with the same arguments. The result of splitAt
is then returned.
You can use this function like this:
main :: IO ()
main = do
let myList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let (firstPart, secondPart) = splitList 5 myList
print firstPart
print secondPart
In this example, myList
is a list of integers. We call the splitList
function with 5
as the index and myList
as the list. The result is stored in the variables firstPart
and secondPart
. We then print both parts of the split list using the print
function.
The output of this program would be:
[1,2,3,4,5]
[6,7,8,9,10]
This shows that the list has been split at index 5
, with the first part containing elements up to index 5
and the second part containing elements starting from index 5
.