Testing functions in Haskell that do IO

后端 未结 5 2120
心在旅途
心在旅途 2020-12-23 17:06

Working through Real World Haskell right now. Here\'s a solution to a very early exercise in the book:

-- | 4) Counts the number of characters in a file
numC         


        
5条回答
  •  一向
    一向 (楼主)
    2020-12-23 17:29

    For that you will need to modify the function such that it becomes:

    numCharactersInFile :: (FilePath -> IO String) -> FilePath -> IO Int
    numCharactersInFile reader fileName = do
                             contents <- reader fileName
                             return (length contents)
    

    Now you can pass any mock function that takes a file path and return IO string such as:

    fakeFile :: FilePath -> IO String
    fakeFile fileName = return "Fake content"
    

    and pass this function to numCharactersInFile.

提交回复
热议问题