LoginSignup
3
1

More than 3 years have passed since last update.

Haskellで逆ポーランド記法の計算機を作る

Last updated at Posted at 2019-12-12

はじめに

いなたつアドカレの十二日目の記事です。

Haskellで逆ポーランド記法の計算機をつくってく記事です

環境構築(Docker)

$ docker run -itd --name haskell -v $PWD:/haskell -w=/haskell haskell

はろわ

とりあえずコマンドライン引数を出力します。

環境構築(Docker)

$ docker run -itd --name haskell -v $PWD:/haskell -w=/haskell haskell
rpn.hs

import System.Environment

main :: IO ()
main = do
    args <- getArgs
    putStrLn $ args !! 0  -- リストの0番目

getArgsでコマンドライン引数をargsに束縛し、 putStrLnで出力、改行を行っています。
Haskellではリスト内の値を「!!」を挟みindex番号で指定することでアクセスすることができます。

つまり、argsというリストの先頭を出力するといった内容になっています。

$ runghc rpn.hs hello
hello
$ runghc rpn.hs Hello World
Hello
$ runghc rpn.hs "Hello World"
Hello World

通常空白でくぎれ、リスト的に値が別れてしまうが、ダブルコーテーションで囲むことで、空白を無視して、一つにまとめることができます

計算する

calc :: String -> Double
calc = head . foldl folding [] . words
    where   folding (x:y:ys) "+" = (y + x):ys
            folding (x:y:ys) "-" = (y - x):ys

文字列を畳み込んで計算させる部分を作成しました。
foldlが左からの畳み込みで、foldingはに引数の計算にあたる関数です

これで、逆ポーランド記法での計算(足し算、引き算)ができるようになりました。

次回これを拡張していきます。

3
1
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
3
1