実現したいこと
Rustプログラムのラムダ式で再帰処理を実装する。
前提
興味本位で試してみたいだけなので、
効率等は問題にしていません。
私はプログラミング経験はあるが、Rustは初心者です。
該当のソースコード
普通にRustで階乗処理を再帰で書けば
以下の様な感じになると思います。
Rust
1fn fact(n: i32) -> i32 { 2 if n <= 1 { 3 1 4 } else { 5 n * fact(n - 1) 6 } 7} 8 9fn main(){ 10 print!("{}",fact(10)) 11}
試したこと
とりあえず、以下を試しました。
Rust
1fn main() { 2 let fact = |n| if n <= 1 { 1 } else { n * fact(n - 1) }; 3 print!("{}", fact(10)); 4}
以下のエラーが発生しました。
error[E0425]: cannot find function fact
in this scope
--> compiler.rs:2:47
|
2 | let fact = |n| if n <= 1 { 1 } else { n * fact(n - 1) };
| ^^^^ not found in this scope
error: aborting due to previous error
For more information about this error, try rustc --explain E0425
.
ラムダ式内から自己参照できない様です。
Javaで同様なことが出来ないか試してみました。
Java
1import java.util.function.*; 2 3class Main { 4 public static void main (String[] args) throws Exception { 5 6 BiFunction<BiFunction, 7 Integer,Integer>fact=(f,x)-> 8 x<=1?1:x*(Integer)f.apply(f,x-1); 9 10 System.out.print(fact.apply(fact,10)); 11 12 } 13}
Javaでは、自己参照の問題は、自分自身を引数として渡してしまえば、回避できるようです。
質問は以下の3点です。
- Rustでも同様の手法で回避できるのか
- 自分自身を渡す場合に型の定義をどうするか
- Rustの特徴を活かした別の解決方法があるのか
以上ですが、よろしくお願いします。
回答1件
あなたの回答
tips
プレビュー