作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 Haskell 程序,它将文件作为输入并将其转换为二叉搜索树。
import System.IO
data Tree a = EmptyBST | Node a (Tree a) (Tree a) deriving (Show, Read, Eq)
ins :: Ord a => a -> (Tree a) -> (Tree a)
ins a EmptyBST = Node a EmptyBST EmptyBST
ins a (Node p left right)
| a < p = Node p (ins a left) right
| a > p = Node p left (ins a right)
| otherwise = Node p left right
lstToTree :: Ord a => [a] -> (Tree a)
lstToTree = foldr ins EmptyBST
fileRead = do file <- readFile "tree.txt"
let a = lstToTree (conv (words file))
return a
conv :: [String] -> [Int]
conv = map read
ins 5 fileRead
<interactive>:2:7:
Couldn't match expected type `Tree a0'
with actual type `IO (Tree Int)'
In the second argument of `ins', namely `fileRead'
In the expression: ins 5 fileRead
In an equation for `it': it = ins 5 fileRead
最佳答案
如果您提供 fileRead
,您将能够立即看到问题。带有类型签名。让我们弄清楚 GHC 将在内部分配给 fileRead
的类型注释。 :
fileRead = do file <- readFile "tree.txt"
let t = lstToTree $ map read $ words file
return t
lstToTree :: Ord a => [a] -> Tree a
, 和
read
总是返回
Read
的成员类型类。所以
t :: (Read a, Ord a) => Tree a
.具体类型取决于文件的内容。
return
将它的参数包装在一个单子(monad)中,所以
return t
类型为
Ord a, Read a => IO (Tree a)
.由于
return t
是
do
中的最后一条语句 block ,它变成
fileRead
的返回类型, 所以
fileRead :: (Read a, Ord a) => IO (Tree a)
fileRead
是
Tree
包裹在
IO
中, 并且不能直接传入
ins
因为它需要
Tree
在其自己的。你不能拿
Tree
出
IO
,但您可以“提升”功能
ins
进入
IO
单子(monad)。
liftM :: Monad m => (a -> r) -> (m a -> m r)
.它接受一个常规函数,并将其变成一个作用于像
IO
这样的单子(monad)的函数。 .它实际上是
fmap
的同义词(在标准 Prelude 中),因为所有单子(monad)都是仿函数。所以这段代码,大致相当于@us202 的,取
fileRead
的结果。 , 插入
5
, 并返回包装在
IO
中的结果.
liftM (ins 5) fileRead
-- or --
fmap (ins 5) fileRead
fmap
版本。此代码仅利用了
IO
是仿函数,所以使用
liftM
向读者暗示你可能也需要它是一个单子(monad)。
fileRead
的最后两行可能应该合并,因为
return
并没有真正做任何事情:
fileRead :: (Read a, Ord a) => IO (Tree a)
fileRead = do file <- readFile "tree.txt"
return $ lstToTree $ map read $ words file
do
完全符号并使用
fmap
再次:
fileRead :: (Read a, Ord a) => IO (Tree a)
fileRead = fmap (lstToTree . map read . words) (readFile "tree.txt")
getLine
不可能是纯的(而且不做 IO 的程序是没用的!)。
getLine
的结果取决于用户输入的内容:您可以运行
getLine
一百万次,每次都得到不同的字符串。 Haskell 利用类型系统将不纯代码标记为
IO
.
IO
单子(monad)。当您想将纯函数带入
IO
时您必须显式(使用
fmap
)或隐式(使用
do
表示法)解除它。
fileRead
版本多于。我用过
fmap
对不纯的
IO
进行操作具有纯函数的数据。
关于 haskell IO : convert IO String to "Other type",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15641584/
我是一名优秀的程序员,十分优秀!