-3

Define the function max2 that takes two integers as arguments and returns the largest of them.

I did this: let max2 x y = if x < y then y else x this I belive is correct

Then define the function max_list that returns the largest of the elements in a nonempty list of integers by calling max2. For the empty list, it should abort with an error message ( raising an exception)

I did this: let list = [3;4] let max_list = if list.IsEmpty then 0 else max2 list.Item(0) list.Item(1) but this wont work if the list is more then two elements. I dont want to use any object-orientated stuff. What is the correct answer?

4

2 に答える 2

3

正解は、リストを使用した再帰について読む必要があるということです。

F#リストは、空のリスト[]と短所(::)コンストラクターを使用して徐々に作成されます。たとえば [3; 4]、はの構文糖衣です3::4::[]。再帰関数を作成する際に、リストでパターンマッチングを使用することがよくあります。

要件に厳密に従った再帰関数は次のとおりです。

let rec max_list xs =
   match xs with
   // The function aborts with an error message on empty lists
   | [] -> invalidArg "xs" "Empty list"
   // Return immediately on a singleton list
   | [x] -> x
   // xs has at least two elements, call max_list 
   // on the bigger element of the first two ones and the rest of the list
   | x1::x2::xs' -> max_list((max2 x1 x2)::xs')

ちなみに、整数でも機能する組み込みの汎用max関数があります。

于 2012-11-20T13:55:17.023 に答える
1

単純な再帰的ソリューション:

let max2 x y = if x < y then y else x

let max_list list =
  let rec loop hi list = 
     match list with 
     | h::t -> let hi = max2 h hi
               loop hi t
     | []   -> hi
  match list with
  | h::t -> loop h t
  | []   -> invalidArg "list" "Empty list"

FSIでのテスト:

> max_list [3;4;5;1;2;9;0];;
val it : int = 9

リスト内の各要素について、前の最高値('hi')と比較します。入力リストが空になるまで、リストの新しい最上位と残りをループ関数に渡します。次に、「こんにちは」を返します。

于 2012-11-20T13:50:21.577 に答える