用Haskell输入数据 [英] Inputting Data with Haskell

查看:113
本文介绍了用Haskell输入数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Back Story :为了更好地理解Haskell和函数式编程,我给了自己一些作业。我的第一项任务是制作一个程序,可以查看数据集(一组数字,博客中的单词等),搜索模式或重复,对它们进行分组,然后报告。



听起来很容易。 :)

问题:我想让程序从文本文件中的数据创建一个列表变量开始。我熟悉 readFile 函数,但我想知道是否有更优雅的方式输入数据。

例如,我我想让用户在命令行中输入类似的内容来加载程序和数据集。


./ haskellprogram textfile.txt

是否有一个函数允许这个?

解决方案

  import System.Environment 

main :: IO()
main = do
args< ; - getArgs
- args是参数列表
如果为空参数
则putStrLnusage:./haskellprogram textfile.txt
else do contents< - readFile $ head args
putStrLn $ doSomething contents

doSomething :: String - >字符串
doSomething =反向

这应该足以让你开始。现在用更有价值的东西来替换 reverse



说到解析一些输入数据,你可能会考虑破坏你的数据转换成 words 使用Prelude中的相应功能。


Back Story: In an attempt to better understand Haskell and functional programming, I've given myself a few assignments. My first assignment is to make a program that can look through a data set (a set of numbers, words in a blog, etc), search for patterns or repetitions, group them, and report them.

Sounds easy enough. :)

Question: I'd like for the program to start by creating a list variable from the data in a text file. I'm familiar with the readFile function, but I was wondering if there was a more elegant way to input data.

For example, I'd like to allow the user to type something like this in the command line to load the program and the data set.

./haskellprogram textfile.txt

Is there a function that will allow this?

解决方案

import System.Environment

main :: IO ()
main = do
  args <- getArgs
  -- args is a list of arguments
  if null args
    then putStrLn "usage: ./haskellprogram textfile.txt"
    else do contents <- readFile $ head args
            putStrLn $ doSomething contents

doSomething :: String -> String
doSomething = reverse

That should be enough to get you started. Now replace reverse with something more valuable :)

Speaking of parsing some input data, you might consider breaking your data into lines or words using respective functions from Prelude.

这篇关于用Haskell输入数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆