Haskell从文件中读取Integer和列表列表 [英] Haskell read Integer and list of lists from file
问题描述
让我说我有一个文件
8 [[1,2,3,4],[1,2]]
其中包含数字和列表列表.
with number and list of lists in it.
此代码允许我从中读取所有行或第n个元素.
This code allow me to read all line or n-th element from it.
import System.IO
main = do
x <- openFile "file.txt" ReadMode
cont <- hGetContents x
let fLines = lines cont
let numb = fLines !! 0 !! 0
print numb
这里numb
是'8'
.
如何在不使用其他库的情况下从numb
获取整数8?
How can I get integer 8 from numb
without using other libraries?
是否有可能读取列表列表并将其用作列表列表?
And is there a possibility to read list of lists and use it as list of lists?
还是我最好将每个列表写在新行中,并逐行阅读并添加到空列表中?
Or should I better write each list in a new row, and read them row by row and add to empty list?
也许这是一个愚蠢的问题,但是我没有找到在互联网上进行类似操作的任何例子.
Maybe it's a stupid question, but I didn't find any example of doing something like that on internet.
更新
感谢分形的回答,我设法写了这篇文章
Thanks to Fractal answer I've managed to write this
rList :: String -> [[Int]]
rList = read
适用于列表列表!
但是,当我无法使用单个Int时.
However, when I cant make it work with single Int.
into :: String -> Int
into = read
不知道为什么,但是不适用于numb
T_T
Don't know why, but it doesn't work for numb
T_T
更新2
好吧,这有点愚蠢. numb
在这里是Char,因此要使其正常工作,就可以编写
Ok, it was kinda stupid. numb
is Char here, so to make it work it will be enough to write
print (into [numb])
谢谢大家的回答.
推荐答案
You can use read
to parse String
representations of Haskell data structures. This should work for your list of lists as well.
这篇关于Haskell从文件中读取Integer和列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!