简体   繁体   English

Haskell逐行打印文件

[英]Haskell printing file line by line

EDIT: New code added and new errors changed too. 编辑:添加了新代码,新错误也发生了变化。 It compiles! 它汇编!

I am a newbie to Haskell, and am running into a problem in a code I'm trying to create for printing lines from a text file. 我是Haskell的新手,并且我正在尝试创建用于从文本文件中打印行的代码中遇到问题。 In doing this, I would need the output of the file to list the lines one by one and number them, and put a row of dashes between lines that don't start with the same character. 在这样做时,我需要文件的输出逐个列出行并对它们进行编号,并在不以相同字符开头的行之间放置一行破折号。 Here is an example of the output I want: 这是我想要的输出示例:

$runghc group.hs (file I input)
1 able
2 academia
3 algae
------
4 carton
------
5 fairway
------
6 hex
7 hockshop

And here is the code that I have currently. 这是我目前的代码。 I think I'm approaching this from the right direction, but I am running into some errors. 我想我是从正确的方向接近这个,但我遇到了一些错误。

import System.Environment (getArgs)

group :: [Char] -> [Char]
group file = printSplit (words (show file)) 1

printSplit (x:[]) n = show n ++ x 
printSplit (x:t) n
       | head x == head (head t) = ((show n) ++ x) ++ printSplit t (n+1)
       | otherwise = ((show n) ++ x ++ "\n------") ++ printSplit t (n+1)

main = do
 args <- getArgs
 bytes <- readFile (head args)
 putStrLn (group bytes)

I am running into this error: 我遇到了这个错误:

*Main> main
1"able\nacademia\nalgae\ncarton\nfairway\nhex\nhockshop\n"

And don't quite yet know how to do with this... 并且还不太清楚如何处理这个......


ORIGINAL POST INFO: A different way I'm attempting is to do words (show file) which will give me 原始帖子信息:我尝试的另一种方式是做一些会给我的文字(显示文件)

["able","academia","algae","carton","fairway","hex","hockshop"]

But I'm not sure where to go after that. 但我不确定那之后会去哪里。 And since I'm trying to learn higher-order functions, maybe someone could explain how to use map or fold to try these to me if possible? 既然我正在尝试学习高阶函数,也许有人可以解释一下如何使用map或fold来尝试这些函数呢? :) :)

Since you're using n in a concatenation, GHC assumes that n is a [Char] . 由于你在串联中使用n ,GHC假设n[Char] However, you want n to be an Int or something similar and use show n whenever you want to transform it to a String . 但是,您希望n成为Int或类似的东西,并且只要您想将它转换为String ,就使用show n

The other error has to do with the return of group . 另一个错误与group的返回有关。 Since group is just printSplit with some fixed parameters, it has the same return type, which is [String] or [[Char]] . 由于group只是带有一些固定参数的printSplit ,因此它具有相同的返回类型,即[String][[Char]] However, putStrLn expects a single String. 但是, putStrLn需要一个String。 You can use unlines or concat in order to concatenate your strings. 您可以使用unlinesconcat来连接字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM