使用Haskell编写一个简单的命令行工具
发布时间:2023-12-09 21:33:11
下面是一个使用 Haskell 编写的简单命令行工具的例子,该工具用于计算两个整数的和:
module Main where
import System.Environment (getArgs)
main :: IO ()
main = do
args <- getArgs
case args of
[x, y] -> do
let result = add (read x) (read y)
putStrLn $ "The sum of " ++ x ++ " and " ++ y ++ " is " ++ show result
_ -> putStrLn "Please provide two integers as arguments."
add :: Int -> Int -> Int
add x y = x + y
这个工具从命令行接收两个整数作为输入,并将它们相加。它使用了 System.Environment 模块中的 getArgs 函数来获取命令行参数。
在 main 函数中,我们首先获取命令行参数,并使用 case 表达式匹配这些参数。如果有且仅有两个参数,则执行计算和输出结果的逻辑,否则输出错误提示信息。
add 函数将两个整数相加,并返回结果。在 main 函数中,我们将从命令行获取的参数作为 Int 类型进行处理。使用 read 函数进行转换,并使用 show 函数将结果转换为字符串。
以下是如何使用该命令行工具的示例:
$ ./add 10 20 The sum of 10 and 20 is 30 $ ./add 5 abc Please provide two integers as arguments.
上述例子为一个简单的 Haskell 命令行工具,用于计算两个整数的和。你可以根据需要进行修改和添加其他功能。
