Haskell奇怪的回归

Arc*_*ler 3 haskell haskell-platform

checkstring :: [String] -> Int -> [String]
checkstring p n = do    z <- doesFileExist (p !! n)
    if z
    then p
    else error $ "'" ++ (p !! n) ++ "' file path does not exist"
Run Code Online (Sandbox Code Playgroud)

它通过查看"n"检查字符串中的元素(因此,如果n = 2,它将检查列表中的第二个字符串),然后查看它是否存在.如果它确实存在,它将返回原始字符串列表,如果不存在则会出错.为什么这样做?:

Couldn't match expected type `[t0]' with actual type `IO Bool'
    In the return type of a call of `doesFileExist'
    In a stmt of a 'do' expression: z <- doesFileExist (p !! n)
Run Code Online (Sandbox Code Playgroud)

Mat*_*rog 6

类型doesFileExistString -> IO Bool.如果您的程序想知道文件是否存在,则必须与文件系统交互,这是一个IO操作.如果您希望您的checkString功能执行此操作,它还必须具有某种基于IO的类型.例如,我认为这样的东西会起作用,虽然我还没有尝试过:

checkstring :: [String] -> Int -> IO [String]
checkstring p n = do    z <- doesFileExist (p !! n)
    if z
    then return p
    else error $ "'" ++ (p !! n) ++ "' file path does not exist"
Run Code Online (Sandbox Code Playgroud)