Haskell从文件中读取并将字符串解析为单词

use*_*551 0 haskell

在ghci模式下,我可以输入以下行:

map read $ words "1 2 3 4 5" :: [Int]
Run Code Online (Sandbox Code Playgroud)

得到[1,2,3,4,5]

当我创建一个名为splitscan.hs的文件,其中包含以下行:

    map read $ words scan :: [Float]
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

[1/1]编译Main(splitscan.hs,splitscan.o)

splitscan.hs:1:1: error:
    Invalid type signature: map read $ words str :: ...
    Should be of form <variable> :: <type>
  |
1 | map read $ words str :: [Float]
  | ^^^^^^^^^^^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

当我这样做:

import System.IO

main = do
    scan <- readFile "g924310_b1_copy.txt"
    map read $ words scan :: [Float]
    putStr scan
Run Code Online (Sandbox Code Playgroud)

我明白了:

readscan.hs:5:5: error:
    • Couldn't match type ‘[]’ with ‘IO’
      Expected type: IO Float
        Actual type: [Float]
    • In a stmt of a 'do' block: map read $ words scan :: [Float]
      In the expression:
        do scan <- readFile "g924310_b1_copy.txt"
             map read $ words scan :: [Float]
           putStr scan
      In an equation for ‘main’:
          main
            = do scan <- readFile "g924310_b1_copy.txt"
                   map read $ words scan :: [Float]
                 putStr scan
Run Code Online (Sandbox Code Playgroud)

问题是,如何实现ghci线,以便我可以从扫描中获取所有单词并列出它们以后我可以适应回归,添加常量等等.

Sil*_*olo 5

在Haskell中,变量是不可变的.所以map read $ words scan不改变变量scan; 它返回一个新值.如果要对其执行某些操作,则需要使用此新值.

import System.IO

main = do
    scan <- readFile "g924310_b1_copy.txt"
    let scan' = map read $ words scan :: [Float]
    print scan'
Run Code Online (Sandbox Code Playgroud)