LoginSignup
6
3

More than 5 years have passed since last update.

Haskellでコマンドライン引数を受け取る

Last updated at Posted at 2018-03-18

こっちで、Pythonでコマンドライン引数を受け取る方法のメモを書いたが、そういえばこっちもやったことなかったので、Haskellでもメモ。

コマンドライン引数を受け取る

System.EnvironmenモジュールのgetArgsを使用する。コマンドライン引数のリストが取得できる。

commandline_args.hs
import           System.Environment (getArgs)

main :: IO ()
main = do
  args <- getArgs
  putStrLn $ args !! 0
  putStrLn $ args !! 1
$ stack runghc commandline_args.hs a b

で実行すると、
出力は、

a
b

となる。
Pythonとは違い、引数リストに実行ファイル名は、含まれない。

実際の使用時

実際使用する際は、おそらく、いくつの引数を受け取ったかを確認し、
さらに、期待する形の入力かをチェックする必要がありそう。

fizzBuzz.hs
import           Data.Char          (isDigit)
import           System.Environment (getArgs)


main :: IO ()
main = do
  let isDigitOnly cs = foldl (\b c -> b && isDigit c ) True cs
  args <- getArgs
  if 1 <= length args
  then do
    let n = (args !! 0)
    if isDigitOnly n
    then
      fizzBuzz (read n :: Int)
    else
      putStrLn "Argument is not digit"
  else
    putStrLn "Arguments are too short"

  return ()

fizzBuzz n
  | n <= 0 = return ()
  | otherwise = do
      fizzBuzz $ n - 1
      fizzBuzz' n

fizzBuzz' n
  | multiplesOf15 = putStrLn $ prefix ++ "FizzBuzz"
  | multiplesOf3  = putStrLn $ prefix ++ "Fizz"
  | multiplesOf5  = putStrLn $ prefix ++ "Buzz"
  | otherwise     = putStrLn $ prefix ++ show n
    where
      multiplesOf3  = n `mod` 3 == 0
      multiplesOf5  = n `mod` 5 == 0
      multiplesOf15 = multiplesOf3 && multiplesOf5
      prefix = show n ++ " : "
  • 引数無し

引数無しエラー

$ stack runghc commandline_args.hs
Arguments are too short
  • 引数が数値じゃない

引数タイプエラー

$ stack runghc commandline_args.hs a
Argument is not digit

  • 引数が数値

正常実行

$ stack runghc commandline_args.hs 15
1 : 1
2 : 2
3 : Fizz
4 : 4
5 : Buzz
6 : Fizz
7 : 7
8 : 8
9 : Fizz
10 : Buzz
11 : 11
12 : Fizz
13 : 13
14 : 14
15 : FizzBuzz
  • 引数が数値で、複数存在

最初の1つを使用し実行

$ stack runghc commandline_args.hs 3 5 15
1 : 1
2 : 2
3 : Fizz
6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3