Case文のパターン

Code Examples for Programming in Scala

型判断と型キャスト

isInstanceOf[String] asInstanceOf[String]

パターンマッチの変数・定数判断

大文字始まりである、バッククオートで包んでいる、this.valueなどのオブジェクトのプロパティ扱いである、場合に定数として扱う 上記以外は、変数扱いとなり、束縛変数ワイルドカードとして機能する。

暗黙のimport

import java.lang._ import scala._ import Predef._

super呼び出し順序

インスタンス自体の呼び出しの次は、右端から順番に線形に処理される。ただし、同じtraitが2回以上登場する場合はその中でも一番左端のものが採用される。 object Main extends App { val first = new FirstClass() first.run() } class SecondClass { def r…

sample code spiral

Code Examples for Programming in Scala Apache License, Version 2.0 import Element.elem object Main extends App { val nSides = 100 println(Spiral.spiral(nSides, 0)) } object Spiral { val space = elem(" ") val corner = elem("+") def spiral(n…

カリー化

object Main extends App { def plainSum(x: Int, y: Int): Int = x + y def curriedSum(x: Int)(y: Int): Int = x + y def first(x: Int): (Int) => Int = (y: Int) => x + y def first1: (Int) => Int = first(1) def first2: (Int) => Int = curriedSum(1)…

GoFパターンをなるべく短文で説明を求められたとき用

Iteratorパターン・・・Iterator[hasNext, next] Adapter・・・異なるインターフェースのオブジェクトを、同じインターフェースで扱う TemplateMethod・・・abstract method FactoryMethod・・・FactoryオブジェクトがProductオブジェクトを作るという話 Sin…

Scala標準APIを利用したリファクタリング例

object Main extends App { def containsNeg1(nums: List[Int]): Boolean = { var exists = false for (num <- nums) if (num < 0) exists = true exists } def containsNeg2(nums: List[Int]): Boolean = nums.exists(_ < 0) def containsOdd1(nums: List[I…

Closureを利用したリファクタリング例

import java.io.File object Main extends App { } object FileMatcher { private def filesHere: Array[File] = new File(".").listFiles def filesEnding(query: String) = for (file <- filesHere; if file.getName.endsWith(query)) yield file def file…

末端再帰

末端再帰に持ち込めれば、「whileループによる実装と同じパフォーマンスまで最適化」を受けることができる。 末端再帰の最適化をオフにするコンパイラオプションは、 -g:notailcalls ただし、Scalaの現状の最適化は、「同じメソッドに対して関数オブジェクト…

名前付き引数とデフォルト引数

object Main extends App { def function1(a: Float = 1, b: Float): Float = { a + 2 * b } function1(b = 3, a = 4) function1(b = 3) }

連続引数

def echo(args: String*): Unit = { for (arg <- args) println(arg) } val arr = Array("1", "2", "3") echo("1", "2") echo(arr: _*)

関数の中に関数

クロージャに相当するものは、変数の実体ではなく、参照をキャプチャーしている。 参照もとがライフサイクル上廃棄されることになった場合は、自動的に値等に再配置される。 import scala.io.Source object Main extends App { processFile("src/Main.scala"…

関数リテラル・部分適用

val f1: (Int) => Int = { (x: Int) => {x}: Int } def sum(a: Int, b: Int, c: Int): Int = { a + b + c } val sum3_1: (Int, Int, Int) => Int = sum val sum3_2: (Int, Int, Int) => Int = sum _ val sum3_3: (Int) => Int = sum3_1(1, _, 3) sum3_1(1,2,…

リテラル

'A' '\u0041' """ | | """.stripMargin 'aSymbol val name = "ab"; s"name is $name ${ 1 * 7 }" raw"\'\\" f"${math.Pi}%08.5f" (1).unary_- == -1 11.0 % 4.0 // 切り捨て除算 math.IEEEremainder(11.0, 4.0) // IEEE754(丸め除算) // リッチラッパー // s…

変数定義

内側のスコープ内でなら重複した変数名で変数定義ができる object Main extends App { scopeCheck() def scopeCheck() = { var i = 1 while ( i <= 10) { var j = 1 while (j <= 10) { print(f"${(i * j).toString}%4s") j += 1 } println() i += 1 } } }

例外構文

object Main extends App { def exception(): Boolean = { try { isEven(1) true } catch { case ex: RuntimeException => ex.printStackTrace() false } finally { // 誤解を防ぐため、finallyで絶対に値を返さない } } def isEven(n: Int): Int = { if (n …

foreign key

ON DELETE/ON UPDATE RESTRICT(親を削除/変更させない) CASCADE(親が削除されたら自分も消える) SET NULL(親が削除されたらnullになる。) NO ACTION (RESTRICTと同じ) 参考 カラムの追加と削除(ALTER TABLE ADD COLUMN,ALTER TABLE DROP COLUMN文) - テーブ…

mysqlコマンド

コマンド $ mysql -u username -p --pager="less -S -n -i -F -X" mysql> show databases; mysql> select database(); mysql> show tables; mysql> desc ${table name}; mysql> show create table ${table name}; mysql> drop table ${table name}; mysql> d…

Swagger

概要 Apiドキュメントサービス リンク Swagger – The World's Most Popular Framework for APIs. Swagger Editor – Swagger 内容 // 起動 $ docker pull swaggerapi/swagger-editor $ docker run -p 80:8080 swaggerapi/swagger-editor

基本一覧

コメント # # =begin =end 制御 if true then else end or if true else end while true end 100.times do end ArrayとHash array = [ 0, 1, 2 ] > [ 0, 1, 2 ] array[0] > 0 array[5] = 5 > [0, 1, 2, nil, nil, 5] array.size > 6 hash = { :key1 => 1, ke…

文字コード マジックコメント

# encoding: UTF-8 <- マジックコメント class Main end ruby - E UTF-8 main.rb irb -E UTF-8

関数 function

shellscript.sunone.me

制御文 if case while for

とあるエンジニアの備忘log: シェル制御文まとめ

Yes/Noで答えるプロンプト 続けますか?プロンプト

qiita.com プロンプト [続けますか?] #!/bin/bash confirm_continuation() { while true; do read -p 'continue? [Y/n]' Answer case $Answer in [Yy]* ) echo continue!; break; ;; [Nn]* ) echo exit!; exit 0; break; ;; * ) echo Please answer YES or N…

クレジットカード番号規則

概要 参考リンク 16文字の数字ペアの最初と最後の数字には意味がある 最初の数字は、クレジットカード会社を示す 最初から15文字は、銀行が決める 最後の1文字は、 The Luhn Algorithm で決まる check digit check digit の出し方 奇数番目の数字について、…

集合 Collectionの結合

図 swift A or B 論理和 / 和集合 / OR A.union(B) A and B 論理積 / 積集合 / AND A.subtract(B) (A or B) and !(A and B) 排他的論理和 / 対象差集合 / XOR A.exclusiveOr(B) A and !B 差集合 A.intersect(B) 図引用:wikipedia

2進数 8進数 10進数 16進数 べき乗

2進数 0b0011 8進数 0o12345670 10進数 1234567890 0123456789 16進数 0x1234abcd べき乗 1.23e1 (= 12.3) 1.23e3 (= 1230) 1.23e-2 (= 0.0123) 0x1.8p0 (=1.5) 0x1.8p1 (=3.0) 0x1.8p-2 (=0.375)

protocolにadaptさせる (適合させる)

概要 クラス宣言時にprotocolを適合させるのではなく、 後からprotocolを適合させる。 例(protocol以外) protocol以外(クラス等)に、Equatableを適合させる。 class Target {} extension Target : Equatable {} func ==(lhs: Target, rhs: Target) -> Bool {…