Haskell:如何解析一个IO输入字符串到一个Float(或Int或其他)? [英] Haskell: How to parse an IO input string into a Float (or Int or whatever)?

查看:153
本文介绍了Haskell:如何解析一个IO输入字符串到一个Float(或Int或其他)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



然而,每次我尝试解析这个函数的时候,输入字符串到浮动我不断收到错误。我试过的每一个方法都没有让我把用户输入的数据变成一个Float,这就是我所需要的。

我的练习程序(不是我试图解决的实际问题)是:

$ $ $ $ $ $ c $ main $
putStrLn请输入一个数字。
inputjar&​​lt; - getLine
read :: read a =>字符串 - > a
putStrLn(read inputjar :: Int)



编辑



还有一个问题。

如何将输入的字符串转换为我可以用于计算的东西?



例如,如何输入字符串以便我可以执行下列操作:

 (var + var)/ 2 


解决方案

  main = do 
putStrLn请输入一个数字。
inputjar < - readLn
print(inputjar :: Int)

是一种更好的方式,因为它立即修复了我们正在阅读的字符串:

$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ putStrLn 请输入一个数字。
inputjar :: Int< - readLn
print inputjar

{ - #LANGUAGE ScopedTypeVariables# - }


I am trying to make a program that takes a Float number inputted by the user via keyboard and does stuff with it.

However every time I try to parse the inputted String into a Float I keep getting errors. Every single method I've tried has failed to allow me to take user inputted data and turn it into a Float, which is what I need.

My practice program (not the actual problem I'm trying to solve) is:

main = do
    putStrLn "Please input a number."
    inputjar <- getLine
    read :: read a => String -> a
    putStrLn( read inputjar :: Int)

Edit

A further question.

How do I take the inputted string and turn it into something I can use in a calculation?

For example, how do I take the inputted string so that I can do something like:

(var + var) / 2

解决方案

main = do
   putStrLn "Please input a number."
   inputjar <- readLn
   print (inputjar :: Int)

This is in a way nicer since it immediately fixes what we're reading the string as:

main = do
   putStrLn "Please input a number."
   inputjar :: Int  <- readLn
   print inputjar

but it requires {-#LANGUAGE ScopedTypeVariables#-}

这篇关于Haskell:如何解析一个IO输入字符串到一个Float(或Int或其他)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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