- 论坛徽章:
- 1
|
这样是不行的。
因为读文件必然伴随着 IO,
因此你只能实现
file2String :: String -> IO String
而不能实现
file2String :: String -> String
这也就是 Haskell 特色之一,它从某种程度避免了程序出现 BUG,同时也更有利于编译器做优化,提高运行时性能。
从另一个角度来理解,同样的文件名,可以得到不同的文件内容(因为文件是在磁盘上的嘛),
因此文件名到文件内容的映射不是 pure functional(所谓的 functional 是指,同样的输入必然得到同样的输出)的,必须得有 IO 的介入。
至于 file2String :: String -> IO String 这个函数,实际上是有的,名字叫 readFile:
- These functions are also exported by the Prelude.
- readFile :: FilePath -> IO String
- The readFile function reads a file and returns the contents of the file as a string. The file is read lazily, on demand, as with getContents.
- .........
复制代码
其中的 FilePath 是 String 的一个同义词/别名:
- type FilePath = String
- File and directory names are values of type String, whose precise meaning is operating system dependent. Files can be opened, yielding a handle which can then be used to operate on the contents of that file.
复制代码
[ 本帖最后由 flw 于 2008-10-23 10:42 编辑 ] |
|