0

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"

7
  • Can you please edit your code, so that it compiles? Some typos and indentation errors. Commented Sep 1, 2013 at 0:38
  • i'm rather green to haskell, don't quite know how to handle these errors. So, any help would suffice. Commented Sep 1, 2013 at 0:40
  • It would help if you could post those errors Commented Sep 1, 2013 at 0:44
  • Could not find module `Data.List.Split' Commented Sep 1, 2013 at 0:45
  • 1
    try: cabal install split in your terminal; do you want to remove all sublists from a list or only prefixes? Commented Sep 1, 2013 at 0:51

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.