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

时间:2018-01-14 19:49:22

标签: haskell

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

map read $ words "1 2 3 4 5" :: [Int]

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

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

    map read $ words scan :: [Float]

我收到此错误:

[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]
  | ^^^^^^^^^^^^^^^^^^^^

当我这样做时:

import System.IO

main = do
    scan <- readFile "g924310_b1_copy.txt"
    map read $ words scan :: [Float]
    putStr scan

我明白了:

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

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

2 个答案:

答案 0 :(得分: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'

答案 1 :(得分:0)

我会做以下事情:

floats :: String -> [Float]
floats = fmap read . words

main :: IO ()
main = print =<< fmap floats readFile "g924310_b1_copy.txt"