haskell程序删除部分列表并打印其余部分

时间:2013-09-01 00:26:13

标签: haskell

如何删除Haskell中列表的一部分?这就是我到目前为止所做的。请告诉我可以做出哪些更改:

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)]

示例:输入“toyboat”输出“boat”

2 个答案:

答案 0 :(得分:1)

以下内容将删除给定列表中的所有子列表:

import Data.List.Split

rmSublist :: Eq a => [a] -> [a] -> [a]
rmSublist [] _ = []
rmSublist _ [] = []
rmSublist xs ys = concat $ filter (/=[]) (splitOn xs ys)

或者,如果您只想删除前缀:

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

答案 1 :(得分:1)

来自stripPrefix

的已存在功能Data.List
 stripPrefix "foo" "foobar" == Just "bar"
 stripPrefix "foo" "foo" == Just ""
 stripPrefix "foo" "barfoo" == Nothing
 stripPrefix "foo" "barfoobaz" == Nothing

定义为

stripPrefix :: Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [] ys = Just ys
stripPrefix (x:xs) (y:ys)
 | x == y = stripPrefix xs ys
stripPrefix _ _ = Nothing

所以,你可以宣布:

removePrefix [] [] = Nothing
removePrefix xs ys = stripPrefix xs ys