I’m trying to make a function in Haskell to split a string at a certain char and a list at a certain number.
For doing this the splitAt function is exactly what I need for numbers, but I can’t give a char with this function.
E.g.
splitAt 5 [1,2,3,4,5,6,7,8,9,10]
gives
([1,2,3,4,5],[6,7,8,9,10])
that is exactly what I needed with the 5 in the left side of the tuple.
But now I want to do this with a char and a string. But splitAt only takes and int for the second argument. I want
splitAt 'c' "abcde"
resulting in
("abc", "de")
I looking for something in the direction of
splitAt (findIndex 'c' "abcde") "abcde"
but the function findIndex returns something of the type Maybe Int and splitAt needs an Int. Then I tried the following
splitAt (head (findIndices (== 'c') "abcde")) "abcde"
This is a possible solution but it returns the following
("ab","cde")
with the c on the wrong side of the tupple. You can add succ to c but what will the result be if the char is a Z.
Is there an easy way to modify to make
splitAt (findIndex 'c' "abcde") "abcde"
work?
You can use
findIndex, just unwrap theMaybeand add one:giving, for example
Maybe is a handy datatype for encoding failure in a way that’s easy to recover. There’s even a function
maybe :: b -> (a -> b) -> Maybe a -> bto use a default value and a function to handle the two cases separately:which also works. For example