4

抽象値を参照に割り当てることができないようで、どうすればよいかわかりません。

open Big_int
let largest = ref zero_big_int;;
let depth = ref zero_big_int;;
let rec big i = (add_int_big_int i zero_big_int)
and collatz = fun num depth ->
  print_endline (string_of_big_int num);
  (if(eq_big_int  (add_int_big_int (-1) num) zero_big_int)then(depth)else(
    if eq_big_int (mod_big_int num (big 2)) zero_big_int then (collatz (div_big_int num (big 2)) (succ_big_int depth)) else (collatz (succ_big_int (mult_int_big_int 3 num)) (succ_big_int depth))))
and euler14 i =
  print_endline (string_of_big_int i);
  (if(lt_big_int i (big 1000000))then (
    let ret = (collatz i unit_big_int) in
    if(ret> !depth)then (largest:=i;depth:=ret; (euler14 (succ_big_int i))) else (euler14 (succ_big_int i))
  ) else (!largest));;
print_endline (string_of_big_int (euler14 (big 2)));;

両方とも Big_nums である maximum:=i と depth:=ret を試すと、コードがクラッシュするようです。これを回避する方法はありますか?

2
2
1
3
3
10
5
16
8
4
2
1
Fatal error: exception Invalid_argument("equal: abstract value")
4

2 に答える 2

6

Big_int.big_inttypeの値を多態的な=, >,と比較することはできません>=Big_int.big_int代わりに、 aが深く埋め込まれている場合でも、a を含むすべての型に対して独自の比較関数を作成する必要があります。

OCaml 3.12.1 以降を使用すると、 Big_int の最新の代替でZ.tある外部ライブラリZarithに実装されている型の値で多相比較関数を使用できます。

ポリモーフィック操作との互換性は、Big_int に対する Zarith の利点の 1 つにすぎません。また、メモリがよりコンパクトで高速です。

于 2013-02-18T05:25:55.097 に答える
0

The thing that's failing seems to be the polymorphic comparison ret > !depth, not the assignment to a ref. I would assume you can use Big_int.compare_big_int.

# let x = big_int_of_int 3;;
val x : Big_int.big_int = <abstr>
# let y = big_int_of_int 4;;
val y : Big_int.big_int = <abstr>
# x > y;;
Exception: Invalid_argument "equal: abstract value".
# compare_big_int x y;;
- : int = -1
# 

(Polymorphic comparison is one of the touchy spots in OCaml.)

于 2013-02-18T05:04:38.217 に答える