Reputation: 11
How do I remove a part of a list in Haskell? This is what I have done so far. Please tell me what are the changes that can be made:
import Data.List
import Data.List.Split
removePrefix :: Eq t => [t] -> [t] -> Maybe [t]
removePrefix [] [] = Nothing
removePrefix ts [] = Just ts
removePrefix (t:ts) (y:ys) =
if inTnFixOf (y:ys) (t:ts) == True
then SrtipPrefix (y:ys) (t:ts)
else Just [(x:xs)]
Example: input "toyboat" output "boat"
Upvotes: 0
Views: 1074
Reputation: 1622
Already exists function stripPrefix
from Data.List
stripPrefix "foo" "foobar" == Just "bar"
stripPrefix "foo" "foo" == Just ""
stripPrefix "foo" "barfoo" == Nothing
stripPrefix "foo" "barfoobaz" == Nothing
is defined as
stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys)
| x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing
So, you could just declare:
removePrefix [] [] = Nothing
removePrefix xs ys = stripPrefix xs ys
Upvotes: 2
Reputation: 2013
the following removes all sublists from a given list:
import Data.List.Split
rmSublist :: Eq a => [a] -> [a] -> [a]
rmSublist [] _ = []
rmSublist _ [] = []
rmSublist xs ys = concat $ filter (/=[]) (splitOn xs ys)
alternatively, if you want to remove only the prefix:
rmPrefix :: Eq a => [a] -> [a] -> [a]
rmPrefix [] ys = ys
rmPrefix _ [] = []
rmPrefix xs ys =
if xs == take n ys
then drop n ys
else ys
where n = length xs
Upvotes: 1