运行《Real World Haskell》第9章示例遇Show类型实例错误求助
No instance for (Show (FilePath -> IO [FilePath])) Error in Real World Haskell Chapter 9 Hey there, let's work through this issue you're hitting with the filesystem traversal example! I remember stumbling on this exact same thing when I first worked through that chapter—so let's break down what's happening and how to fix it.
What's Causing the Error?
First, let's unpack that error message. When you run foldTree atMostThreePictures [] in GHCi, you're getting back a function: specifically, a value of type FilePath -> IO [FilePath].
GHCi's default behavior is to take the result of whatever expression you run, try to convert it to a string (using the Show typeclass), and print it out. But functions don't have a Show instance—Haskell doesn't know how to turn a function like "take a filepath and return an IO action of filepaths" into a readable string. That's exactly what the error is telling you: there's no way to print this function value.
How to Fix It
The problem is that you haven't finished calling the function! foldTree builds a traversal function, but you need to pass it a root directory path to actually run the traversal and get an IO action that produces a list of files (which can be printed).
Try one of these approaches:
1. Call the function directly with a directory path
Pass a filepath (like the current directory ".") to the result of foldTree:
foldTree atMostThreePictures [] "."
GHCi will execute this IO action, run the directory traversal, and print out the list of matching files (in your case, up to three pictures).
2. Assign the traversal function to a variable first (for clarity)
If you want to split it up to see what's happening:
-- Build the traversal function let pictureTraverser = foldTree atMostThreePictures [] -- Run it on the current directory pictureTraverser "."
This does the exact same thing as the first approach, but makes it clearer that foldTree is creating a reusable traversal function.
Why the print Reference?
The error mentions print because that's what GHCi is trying to do automatically with your expression's result. When you type an expression in GHCi, it's equivalent to running:
print (foldTree atMostThreePictures [])
Since foldTree ... [] returns a function, and print requires its argument to have a Show instance, you get that error. Once you pass a filepath, you get an IO [FilePath]—GHCi knows how to execute this IO action, and then print the resulting [FilePath] list (since lists of strings have a Show instance).
内容的提问来源于stack exchange,提问作者Tae

