基于var的更改值

发布于 2025-02-03 00:39:12 字数 748 浏览 1 评论 0原文

我正在尝试从文件(Integer,char ...)中读取一种类型的输入,并根据类型文件读取值。

我的问题是我的输入是整数我必须要 让Value = read contents :: int如果我的输入是char let value = read read contents :: string我的处理方式是使用两个不同的文件,我已经试图实施几个条款,但到目前为止什么都没有。我能做的最好的方法是什么?

import System.Environment
import System.IO
import Data.List
import Data.Typeable

---------------------------
{ HASKELL CODE } (problem:)
---------------------------

main :: IO()

main = do
   args <- getArgs
   contents <- readFile (head args)
   let var = (show (typeOf contents))

   if var == "[Char]" then
       let value = read contents::String
   else if var == "[Int]"
       let value = read contents::Int
   else
       putStrLn "test"

   print(problem value)

I'm trying to read a type of input from a file (Integer, Char...), and let the value depending on the type file.

My problem is if my input is an Integer i have to
let value = read contents::Int if my input is Char let value = read contents::String the way im dealing with this is using two different files, i've tried to implement several if clauses but nothing worked so far. whats the best way i can do to approach this?

import System.Environment
import System.IO
import Data.List
import Data.Typeable

---------------------------
{ HASKELL CODE } (problem:)
---------------------------

main :: IO()

main = do
   args <- getArgs
   contents <- readFile (head args)
   let var = (show (typeOf contents))

   if var == "[Char]" then
       let value = read contents::String
   else if var == "[Int]"
       let value = read contents::Int
   else
       putStrLn "test"

   print(problem value)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

雨后彩虹 2025-02-10 00:39:12

一种方法是使用

parse :: String -> Either Int String
parse s = case readMaybe s of
    Just n -> Left n
    _ -> Right s

doSumthin :: Either Int String -> IO ()
doSumthin (Left 7) = print 50
doSumthin (Right "Santa is real") = putStrLn "Santa is fake"

您可以进行辩护:

parseAndDoSumthin :: String -> IO ()
parseAndDoSumthin s = case (readMaybe s :: Maybe Int, s) of
    (Just 7, _) -> print 50
    (Nothing, "Santa is real") -> putStrLn "Santa is fake"

One way is to use Either:

parse :: String -> Either Int String
parse s = case readMaybe s of
    Just n -> Left n
    _ -> Right s

doSumthin :: Either Int String -> IO ()
doSumthin (Left 7) = print 50
doSumthin (Right "Santa is real") = putStrLn "Santa is fake"

You could deforest:

parseAndDoSumthin :: String -> IO ()
parseAndDoSumthin s = case (readMaybe s :: Maybe Int, s) of
    (Just 7, _) -> print 50
    (Nothing, "Santa is real") -> putStrLn "Santa is fake"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文