使用'print'

时间:2018-05-22 22:17:44

标签: haskell ghci

我正在尝试修复并运行真实世界Haskell书籍中的每个示例,并在此过程中学习一些东西,我被困在chapter 9。通过阅读评论,我得到了以下代码来编译:

FoldDir.hs

import ControlledVisit
import Data.Char (toLower)
import Data.Time.Clock (UTCTime(..))
import System.Directory (Permissions(..))
import System.FilePath ((</>), takeExtension, takeFileName)

data Iterate seed
  = Done { unwrap :: seed }
  | Skip { unwrap :: seed }
  | Continue { unwrap :: seed }
    deriving (Show)

type Iterator seed = seed -> Info -> Iterate seed

foldTree :: Iterator a -> a -> FilePath -> IO a
foldTree iter initSeed path = do
  endSeed <- fold initSeed path
  return (unwrap endSeed)
  where
    fold seed subpath = getUsefulContents subpath >>= walk seed
    walk seed (name : names) = do
      let path' = path </> name
      info <- getInfo path'
      case iter seed info of
        done @ (Done _) -> return done
        Skip seed'      -> walk seed' names
        Continue seed'
          | isDirectory info -> do
            next <- fold seed' path'
            case next of
              done @ (Done _) -> return done
              seed''           -> walk (unwrap seed'') names
          | otherwise         -> walk seed' names
    walk seed _ = return (Continue seed)

atMostThreePictures :: Iterator [FilePath]
atMostThreePictures paths info
  | length paths == 3
    = Done paths
  | isDirectory info && takeFileName path == ".svn"
    = Skip paths
  | extension `elem` [".jpg", ".png"]
    = Continue (path : paths)
  | otherwise
    = Continue paths
  where
    extension = map toLower (takeExtension path)
    path = infoPath info

countDirectories count info =
  Continue (if isDirectory info then count + 1 else count)

ControlledVisit.hs

module ControlledVisit where

import Control.Monad (forM, liftM)
import Data.Time.Clock (UTCTime(..))
import System.FilePath ((</>))
import System.Directory
  ( Permissions(..)
  , getModificationTime
  , getPermissions
  , getDirectoryContents
  )
import Control.Exception
  ( bracket
  , handle
  , SomeException(..)
  )
import System.IO
  ( IOMode(..)
  , hClose
  , hFileSize
  , openFile
  )

data Info = Info
  { infoPath :: FilePath
  , infoPerms :: Maybe Permissions
  , infoSize :: Maybe Integer
  , infoModTime :: Maybe UTCTime
  } deriving (Eq, Ord, Show)

getInfo :: FilePath -> IO Info
getInfo path = do
  perms <- maybeIO (getPermissions path)
  size <- maybeIO (bracket (openFile path ReadMode) hClose hFileSize)
  modified <- maybeIO (getModificationTime path)
  return (Info path perms size modified)

traverseDirs :: ([Info] -> [Info]) -> FilePath -> IO [Info]
traverseDirs order path = do
  names <- getUsefulContents path
  contents <- mapM getInfo (path : map (path </>) names)
  liftM concat $ forM (order contents) $ \ info -> do
    if isDirectory info && infoPath info /= path
      then traverseDirs order (infoPath info)
      else return [info]

getUsefulContents :: FilePath -> IO [String]
getUsefulContents path = do
  names <- getDirectoryContents path
  return (filter (`notElem` [".", ".."]) names)

isDirectory :: Info -> Bool
isDirectory = maybe False searchable . infoPerms

maybeIO :: IO a -> IO (Maybe a)
maybeIO act = handle (\ (SomeException _) -> return Nothing) (Just `liftM` act)

traverseVerbose order path = do
  names <- getDirectoryContents path
  let usefulNames = filter (`notElem` [".", ".."]) names
  contents <- mapM getEntryName ("" : usefulNames)
  recursiveContents <- mapM recurse (order contents)
  return (concat recursiveContents)
  where
    getEntryName name = getInfo (path </> name)
    isDirectory info = case infoPerms info of
      Nothing -> False
      Just perms -> searchable perms
    recurse info = do
      if isDirectory info && infoPath info /= path
        then traverseVerbose order (infoPath info)
        else return [info]

但是当我尝试在GHCi as explained in the book中运行它时,它失败并出现了一个奇怪的错误,据我所知,这是关于GHCi本身的:

Prelude> :l FoldDir.hs
[1 of 2] Compiling ControlledVisit  ( ControlledVisit.hs, interpreted )
[2 of 2] Compiling Main             ( FoldDir.hs, interpreted )
Ok, two modules loaded.
*Main> foldTree atMostThreePictures []

<interactive>:2:1: error:
    • No instance for (Show (FilePath -> IO [FilePath]))
        arising from a use of ‘print’
        (maybe you haven't applied a function to enough arguments?)
    • In a stmt of an interactive GHCi command: print it

我想我理解No instance for (Show (FilePath -> IO [FilePath]))部分,但我对print it一无所知。我知道it是GHCi中的一个特殊变量,它存储了最后一个表达式的评估结果,我想代码正在尝试打印函数或monad,但我不知道它发生了什么。

1 个答案:

答案 0 :(得分:2)

尽可能简单 - 您的函数foldTree的签名是:

foldTree :: Iterator a -> a -> FilePath -> IO a

您正在为它提供两个参数,一个类型为Iterator [FilePath],另一个类型为FilePath。由于默认的部分应用,这种调用返回带签名的函数:

FilePath -> IO [FilePath]

GHCI希望显示您的调用结果但不能,因为此类型没有已定义的类型类Show的实例。所以,它给你一个错误的确切地告诉你。