![](/img/trans.png)
[英]Haskell record syntax and read from file. String to record syntax. *** Exception: Prelude.read: no parse
[英]Haskell Read from file and parse string into words
在ghci模式下,我可以输入以下行:
map read $ words "1 2 3 4 5" :: [Int]
并获得[1,2,3,4,5]
当我创建一个名为splitscan.hs的文件时,包含以下内容:
map read $ words scan :: [Float]
我收到此错误:
[1 of 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行,以便我可以从扫描中获取所有单词并列出它们的列表,以便以后适合回归,向等添加常量。
在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'
我将执行以下操作:
floats :: String -> [Float]
floats = fmap read . words
main :: IO ()
main = print =<< fmap floats readFile "g924310_b1_copy.txt"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.