应用String类型的函数 - > [String] - > [String]到两个[String]

时间:2015-03-24 14:57:23

标签: string list function haskell types

我努力想出一个好头衔。

这里是要点:

我有一个函数(remIgnored),它打算从字符串列表中删除字符串。

module Main(main) where

import System.Environment
import Data.List
import Data.Char

getLines :: FilePath -> IO [String]
getLines path = do 
    ls <- readFile path
    return (lines ls)

getWords :: [String] -> [String]
getWords ws = words (unlines ws)

remIgnored :: String -> [String] -> [String]
remIgnored _ []                 = []
remIgnored x (y:ys) | x == y    = remIgnored x ys
                    | otherwise = y : remIgnored x ys

main :: IO ()
main = do
    args <- getArgs
    let path = args !! 0
    let ignore = args !! 1
    ig <- getLines ignore
    ls <- getLines path
    let ig'  = map (map toLower) (getWords ig)
    let ls'  = map (map toLower) (getWords ls)
    let ls'' = sort ls'
    putStrLn "Original Lines:\n"
    mapM_ putStrLn ls
    putStrLn "\nLower Cased Words:\n"
    mapM_ putStrLn ls'
    putStrLn "\nLower Cased Words + Sorted:\n"
    mapM_ putStrLn ls''
    putStrLn "\nLower Cased Words + Sorted + Sanitized:\n"
    --Something nice goes here

(请忽略对列表进行细微更改的不断复制,我只是在讨论它们是如何工作的。)

基本上,我的问题是:如何将remIgnored函数应用于ls''中的每个元素的列表ig'?我整晚都在盯着类型错误,而且我的进展甚微(即使我到目前为止已经给我带来了很大的烦恼)。

供参考,我的输入文件:

test.txt

The quick brown fox jumps over the lazy dog
Peter picked a pail of pickled peppers
She sells sea shells by the sea shore

ignore.txt

a
the
of
by

示例输出:

Original Lines:
The quick brown fox jumps over the lazy
Peter picked a pail of pickled peppers
She sells sea shells by the sea shore

Lower Cased Words:
the
quick
brown
fox
jumps
over
the
lazy
dog
peter
picked
a
pail
of
pickled
peppers
she
sells
sea
shells
by
the
sea
shore

Lower Cased Words + Sorted:
a
brown
by
dog
fox
jumps
lazy
of
over
pail
peppers
peter
picked
pickled
quick
sea
sea
sells
she
shells
shore
the
the
the

Lower Cased Words + Sorted + Sanitized:

1 个答案:

答案 0 :(得分:5)

实际上,你应该使用折叠来做到这一点。

remAllIgnored :: [String] -> [String] -> [String]
remAllIgnored = flip $ foldr remIgnored

是的,这真的很简单。

如果您对折叠不满意,可以使用ignore-list的递归显式编码:

remAllIgnored [] words = ... -- nothing to ignore means: ?
remAllIgnored (ign0:igns) words
    = let ??  -- somehow you need to 1. apply the `ign0`-ignore-patch
      in ??   --                     2. process the rest of the `igns`

尝试一下,如果有任何特殊问题,请回复一下。