Haskell 美元符号在putStrLn函数中的用法

Haskell 美元符号在putStrLn函数中的用法,haskell,Haskell,这是我写的一个简单的程序 import System.Environment import System.IO main = do (fileName1:_) <- getArgs contents <- readFile fileName1 let myList = lines contents totalLines = length myList putStrLn $ "Total lines in the files are " ++ show (

这是我写的一个简单的程序

import System.Environment
import System.IO

main = do
  (fileName1:_) <- getArgs
  contents <- readFile fileName1
  let myList = lines contents
      totalLines = length myList
  putStrLn $ "Total lines in the files are " ++ show (totalLines) ++ " lines"
导入系统环境
导入系统.IO
main=do

(fileName1:p>
$
是一个运算符,它将右侧的值传递给左侧的函数。以下是它的实现方式:

f $ x = f x
它很有用,因为它的运算符优先级很低,因此在您的示例中,首先应用
++
运算符,从而生成
$
函数接受并传递给
putStrLn
的字符串

在您的示例中,如果没有
$
,Haskell将尝试按以下顺序计算该行:

(putStrLn "Total lines in the files are ") ++ show (totalLines) ++ " lines"
因此,它将尝试打印第一个字符串,然后获取
putStrLn
的结果并将其与其他字符串连接,这会导致错误,因为
putStrLn
不返回字符串