简体   繁体   English

第一个Haskell IO程序无法正常工作

[英]First Haskell IO program isn't working

Sorry, this is probably really dumb, but can someone explain me why this program doesn't compile? 抱歉,这可能真是愚蠢,但是有人可以向我解释为什么该程序无法编译吗? I get Couldn't match expected type 'a1 -> String' with actual type 'IO String' . Couldn't match expected type 'a1 -> String' with actual type 'IO String'

import System.Environment

main = do
  [first, last] <- getArgs
  firstnames <- lines . readFile "firstnames_male"
  lastnames <- lines . readFile "lastnames"
  print firstnames

You can't do lines . readFile "lastnames" 你不能做lines . readFile "lastnames" lines . readFile "lastnames" . lines . readFile "lastnames"

The readFile function returns an IO String , not a String . readFile函数返回IO String ,而不是String

You can , however, use the fmap function (or the <$> operator) to achieve this: 但是,您可以使用fmap函数(或<$>运算符)来实现此目的:

main = do
  [first, last] <- argArgs
  firstnames <- lines `fmap` readFile "firstnames_males"
  ...

This works because IO is a functor. 之所以IO是因为IO是函子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM