LoginSignup
0
0

《プログラミングの基礎》をReScriptで読む 第6章-第7章

Last updated at Posted at 2024-04-25

《プログラミングの基礎》はとても良い本です。
サンプルプログラムをReScriptで書いて、プログラミングの基礎とReScriptを学びます。

環境

  • macOS Sonoma(バージョン 14.4.1)
  • ReScript 11.1.0-rc.8
  • @rescript/core 1.2.0

第6章

エラーの説明だけです。

第7章

組が紹介されます。タプルと呼ぶ方が一般的な気がします。

OCaml
match  with
  パターン -> 
ReScript
switch  {
| パターン => 

OCamlのmatchは、ReScriptのswitchになります。

Ex07_1.res
// 目的:5教科の点数の合計点と平均点を組にして返す
// goukei_to_heikin : int -> int -> int -> int -> int -> int * int
let goukei_to_heikin = (kokugo, suugaku, eigo, rika, shakai) =>
  (kokugo + suugaku + eigo + rika + shakai,
    (kokugo + suugaku + eigo + rika + shakai) / 5)

// テスト
Console.log(goukei_to_heikin(80, 100, 90, 85, 75) == (430, 86))
Console.log(goukei_to_heikin(90, 70, 95, 65, 90) == (410, 82))
Console.log(goukei_to_heikin(60, 50, 70, 55, 65) == (300, 60))
Ex07_2.res
// 目的:名前と成績の組を受け取ったら、その評価文を返す
// seiseki : string * string -> string
let seiseki = (pair) => switch pair {
| (namae, seiseki0) => namae ++ "さんの成績は " ++ seiseki0 ++ " です。"
}

//テスト
Console.log(seiseki(("浅井", "C")) == "浅井さんの成績は C です。")
Console.log(seiseki(("中村", "A")) == "中村さんの成績は A です。")
Console.log(seiseki(("出原", "B")) == "出原さんの成績は B です。")
Ex07_3.res
// 目的:組で表された平面座標を受け取ったら x 軸に対称な点の座標を返す
// taisho_x : float * float -> float * float
let taisho_x = (point) => switch point { 
| (x, y) => (x, -. y) 
}
 
// テスト
Console.log(taisho_x((0.0, 0.0)) == (0.0, 0.0))
Console.log(taisho_x((2.3, 5.1)) == (2.3, -5.1)) 
Console.log(taisho_x((-3.8, -2.4)) == (-3.8, 2.4))
Ex07_4.res
// 目的:組で表された平面座標をふたつ受け取ったら、その中点の座標を返す
// chuten : float * float -> float * float -> float * float
let chuten = (point1, point2) => switch point1 { 
| (x1, y1) => switch point2 { 
	|	(x2, y2) => ((x1 +. x2) /. 2.0, (y1 +. y2) /. 2.0) 
  }
}

// テスト
Console.log(chuten((0.0, 0.0), (1.0, 2.0)) == (0.5, 1.0))
Console.log(chuten((2.3, 5.1), (7.6, 1.7))/* == (4.95, 3.4) */)
Console.log(chuten((-3.8, -2.4), (3.4, -1.2))/* == (-0.2, -1.8) */)
0
0
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
0
0