read_int関数とread_float関数
from マルチサイクル RISC-V CPU を作成したい
以下のような read_int と read_float を実装したい。
code:c
float min_caml_read_float() {
float f;
fscanf(fp, "%f", &f);
// scanf("%f", &f);
return f;
}
int min_caml_read_int() {
int i;
fscanf(fp, "%d", &i);
// scanf("%d", &i);
return i;
}
read_float関数
read_float を雑に実装。 手元の MinCaml で && が使えないのが地味に面倒だった。
ワンパス通すの優先で、エラーハンドリングはだいぶ雑な感じ。困ってから対応しよう。
code:read_float_test.ml
let rec read_float _ =
(* 小数部分をパース *)
let rec parse_fraction _ =
let c = read_byte () in
if c >= 48 then
if c <= 57 then
(* 0 ~ 9 の場合 *)
let i = float_of_int (c - 48) in
i +. parse_fraction () /. 10.0
else
(* 数字以外が来たら、パースを終える *)
0.0
else
(* 数字以外が来たら、パースを終える *)
0.0
in
(* 整数部分をパース *)
let rec parse_float acc =
let c = read_byte () in
if c = 46 then
(* "." の場合、小数点部分を読み込む *)
acc +. (parse_fraction () /. 10.0)
else if c >= 48 then
if c <= 57 then
(* 0 ~ 9 の場合 *)
let i = float_of_int (c - 48) +. acc *. 10.0 in
parse_float i
else
(* 数字以外が来たら、パースを終える *)
acc
else
(* 数字以外が来たら、パースを終える *)
acc
in
let c = read_byte () in
if c = 32 then
(* 空白の場合、次のトークン取得へ *)
read_float ()
else if c = 9 then
(* TAB の場合、次のトークン取得へ *)
read_float ()
else if c = 10 then
(* 改行の場合、次のトークン取得へ *)
read_float ()
else if c = 13 then
(* 改行の場合、次のトークン取得へ *)
read_float ()
else if c = 45 then
(* "-" の場合 *)
(parse_float 0.0) *. -1.0
else if c >= 48 then
if c <= 57 then
(* 0 ~ 9 の場合 *)
parse_float (float_of_int (c - 48))
else
(* エラーっぽい値を返しておく *)
-11111.0
else
(* エラーっぽい値を返しておく *)
-11111.0
in
print_int (int_of_float (read_float () *. 1000.0));
print_newline ()
read_int関数
こちらも雑に実装。整数の掛け算が未実装だったので acc * 10 の代わりに acc + acc + acc + acc + ... になってるところに悲哀を感じる。
code:read_int_test.ml
let rec read_int _ =
(* let read_byte () = input_byte stdin in *)
(* 整数部分をパース *)
let rec parse_int acc =
let c = read_byte () in
if c >= 48 then
if c <= 57 then
(* 0 ~ 9 の場合 *)
let i = (c - 48) + (acc + acc + acc + acc + acc + acc + acc + acc + acc + acc) in
parse_int i
else
(* 数字以外が来たら、パースを終える *)
acc
else
(* 数字以外が来たら、パースを終える *)
acc
in
let c = read_byte () in
if c = 32 then
(* 空白の場合、次のトークン取得へ *)
read_int ()
else if c = 9 then
(* TAB の場合、次のトークン取得へ *)
read_int ()
else if c = 10 then
(* 改行の場合、次のトークン取得へ *)
read_int ()
else if c = 13 then
(* 改行の場合、次のトークン取得へ *)
read_int ()
else if c = 45 then
(* "-" の場合 *)
0 - (parse_int 0)
else if c >= 48 then
if c <= 57 then
(* 0 ~ 9 の場合 *)
parse_int (c - 48)
else
(* エラーっぽい値を返しておく *)
-11111111
else
(* エラーっぽい値を返しておく *)
-11111111
in
let rec loop _ =
let i = read_int () in
print_int i;
print_newline ();
loop ()
in
loop ()