2014-07-26 5 views
2

제목에서 알 수 있듯이 주어진 경로에서 주어진 문자열을 찾으려고합니다. 여기에 지금까지 올 것입니다 :주어진 경로에서 주어진 문자열 찾기

getRecursiveContents :: FilePath -> IO [FilePath] 
getRecursiveContents topdir = do 
    names <- getDirectoryContents topdir 
    let properNames = filter (`notElem` [".", ".."]) names 
    paths <- forM properNames $ \name -> do 
    let path = topdir </> name 
    isDirectory <- doesDirectoryExist path 
    if isDirectory 
     then getRecursiveContents path 
    else return [path] 
    return (concat paths) 

findInFile:: String -> FilePath -> IO Bool 
findInFile needle filePath= do 
    content <- readFile filePath 
    return (needle `L.isInfixOf` content) 

findInFolder:: (String -> Bool) -> FilePath -> String -> IO [IO Bool] 
findInFolder p path needle = do 
    files <- getRecursiveContents path 
    return (map (findInFile needle) (filter p files)) 

find = findInFolder (\p -> takeExtension p `elem` [".py", ".xml", ".html"]) 

I 할 수 있습니다

완벽하지만 폴더에 대한 동일한 검색 할 수없는
*Main> findInFile "search_string" "./path/to/a/file" 
True 

: 내 파일에서

*Main> find "./path/to/a/folder" "search_string" 
*Main> 

을 시스템 ./path/to/a/file./path/to/a/folder에 있습니다. 따라서 나는 동일한 결과를 기대하고 있었다.

내가 뭘 잘못하고 있니?

참고 : getRecursiveContentsreal world haskell입니다.

답변

3

실제로 작동합니다. 유일한 문제는 사물이 인쇄되는 방법입니다. ghci에 일부 표현식을 입력하면 해당 표현식에 print이 호출됩니다. 값이 IO x 인 경우 IO 작업을 실행하고 인 경우에만 Show 인스턴스가있는 경우에만 x을 인쇄하십시오. 그렇지 않으면 추가 정보를 인쇄하지 않습니다. find "./path/to/a/folder" "search_string"IO 작업 목록을 생성하며 어떤 작업도 Show 인스턴스가 아닙니다. 당신은 IO 작업의 목록이 다시 인 find의 결과를 얻을, 다음을 실행할 수 있습니다

> x <- find "./path/to/a/folder" "search_string" 
> sequence x 
> [True, False ... 

가능성 당신은 당신의 기능에 원래 이렇게하고 싶었다. 다음과 같이 변경하면됩니다.

findInFolder:: (String -> Bool) -> FilePath -> String -> IO [Bool] 
findInFolder p path needle = do 
    files <- getRecursiveContents path 
    mapM (findInFile needle) (filter p files) 

이제는 예상대로 작동합니다.

관련 문제