LoginSignup
3
1

More than 5 years have passed since last update.

rustとscalaとkotilnの勉強 数当てゲーム(kotlin) 2回目 と3つやってみた感想

Last updated at Posted at 2018-07-05

TRPLの数当てゲーム。
kotlinもループを使わずに書いてみる。
kotlinにはeitherとかoptionとかmaybe みたいなものがない。
エラーハンドリングもtry-catchしかない。
成功失敗と戻り値を戻したかったのでとりあえずPairで逃げておいた。

結構色々ないkotlin。
・・・と思いきやジェネレータはある。
ただしthe feature "coroutines" is experimental
yieldでシーケンスを作れるのはやっぱり楽。
rustにも早くこないかな。
kotlin.coroutines.experimental.buildSequenceで無限リストをつくるようにした。
ネームスペースにcoroutinesと入っているのを見てもわかるように、ジェネレータに特化したものではなく、コルーチン諸々があってジェネレータはその一部、みたいな感じっぽい。
ほかの機能はみてないけど。たぶん。

import java.util.Random
import kotlin.coroutines.experimental.buildSequence
fun main(args:Array<String>){
    val secret_number = Random().nextInt(99) + 0
    println("秘密の数字は次の通り:${secret_number}")
    println("数をあててごらん")
    println("ほら予想を入力してね")
    buildSequence{
        while(true){
            yield(readLine())
        }
    }.map{
        s->try{
            Pair(true,Integer.parseInt(s))
        }catch(e:Exception){
        Pair(false,0)
        }
    }.filter{
        p->p.first
    }.map{
        p->p.second
    }.map{
        i-> when{
            i==secret_number -> {println("正解");i}
            i<secret_number -> {println("小さ過ぎる");i}
            else -> {println("大き過ぎる");i}
        }
    }.filter{
        i->i==secret_number
    }.first()
}

書いてて思ったけど、mapとかfilterとかでチェーンしていく中でエラーが起きる可能性がある処理が挟まるとやっぱりeitherなりrustのresultみたいなのがないとなんかイマイチ。
scala,rust,kotlinだとやっぱscalaが一番かきやすかった気もする。
scala>>>>rust,kotlinかなあ。
rustはコンパイラとの戦いが辛かった。
kotlinは、、、一番文法を調べずに書いてるのでしょうもないことで時間がかかった。
{をどうしても(と書いちゃって・・・

あと、rustはコンパイラとの戦いが辛いんだけど、コンパイルエラーの内容が本当に親切。
rustになれると他の言語のコンパイルエラーが心もとなく感じる。

いいかげん数当てゲームはやめて先にすすまねば・・・

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