Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
Help us understand the problem. What is going on with this article?

Haskellでfor文

More than 3 years have passed since last update.

Haskellの勉強始めたけどfor文が無くて困ったので作ってメモしておく。

print n してるとこにやりたい処理(関数)書けばいわゆるfor文のように使えるかなと、できることなら関数ポインタ?渡して汎用化したいけどHaskellそこまで分からないので必要になる都度に下記のようなコード作っていこうかなという感じです。
そもそもHaskellの思想を察するとfor文滅多に必要にならないはずなので汎用化の必要は無いのかもしれない。

eachUpTo n max
    | n > max = error "だめだよ"
    | n == max = do
        return max
    | otherwise = do
        print n
        return =<< eachUpTo (n + 1) max

eachDownTo n min
    | n < min = error "だめだよ"
    | n == min = do
        return min
    | otherwise = do
        print n
        return =<< eachDownTo (n - 1) min

eachDown i
    | i < 0 = error "だめだよ"
    | i == 0 = do
        return 0
    | otherwise = do
        print i
        return =<< eachDown (i - 1)

main = do
    putStrLn "eachUpTo 0 10"
    print =<< eachUpTo 0 10
    putStrLn "eachDownTo 10 0"
    print =<< eachDownTo 10 0
    putStrLn "eachDown 10"
    print =<< eachDown 10
    --
    --print =<< eachUpTo 100 10
    --print =<< eachDownTo 10 100
    --print =<< eachDown (-1)
eachUpTo 0 10
0
1
2
3
4
5
6
7
8
9
10
eachDownTo 10 0
10
9
8
7
6
5
4
3
2
1
0
eachDown 10
10
9
8
7
6
5
4
3
2
1
0
ikuo0
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away