再帰関数comp

テクノロジ系難易度: ★★★★

文字列を引数とする関数 len, first, butfirst を用いて、関数 comp を再帰的に定義した。comp("11", "101") を呼び出したとき、返される値はどれか。

【関数の定義】

  • len(S): 文字列Sの長さを返す。Sが空文字列のときは0を返す。
  • first(S): 文字列Sの先頭の1文字のASCIIコードを返す。Sが空文字列のときはエラーを返す。
  • butfirst(S): 文字列Sの先頭の1文字を除いた残りの文字列を返す。Sが空文字列のときはエラーを返す。
comp(A, B)
begin
  if len(A) = 0 and len(B) = 0 then return 0;
  if len(A) = 0 and len(B) ≠ 0 then return 1;
  if len(A) ≠ 0 and len(B) = 0 then return −1;
  if first(A) < first(B) then return 1;
  if first(A) > first(B) then return −1;
  return comp(butfirst(A), butfirst(B));
end
出典: 平成21年度春期 応用情報技術者 午前 問7