2016-04-18 25 views
0

私は自分のOCamlコードに不一致が発生していますが、何が問題なのかわかりません。私は唯一のケースを持つと問題がアップ出番を把握するためにそこから行く試みたが、私が受け取るエラーは、次のとおりです。一致失敗問題OCaml

Exception: Match_failure ("hw2.ml", 49, 0). 

コード:

let rec compileStack(il : instr list) (st : float list) = 
match (il,st) with 
[],[_] -> List.hd st 
|((Push f)::t),[_] -> compileStack t (f::st) 
|(Swap)::t, h2::h1::st -> compileStack t (h2::h1::st) 
|(Calculate op)::t, h1::h2::st -> 
    match op with 
    Plus -> compileStack t (h2+.h1::st) 
    | Minus -> compileStack t (h2-.h1::st) 
    | Times -> compileStack t (h2*.h1::st) 
    | Divide -> compileStack t (h2/.h1::st) ;;        

let execute (li : instr list) : float = 
    let stack = [] in 
    compileStack li stack;; 

任意の提案は非常に立ち往生され、理解されるであろうこれで2時間今

+1

ここで、ライン49ですか? –

+2

失敗したテストの入力データは何ですか?ちなみに、(il、st)のパターンマッチングは網羅的なものではありません。これはあなたの問題だと思われます。 –

答えて

2

コンパイル時に注意してください。それが何かのように言うならば、

Warning ...: this pattern-matching is not exhaustive. 

のように表示されることがあります。ちなみに、コンパイラは、逃したケースの例を提供します。

あなたの問題を考えて、私は別の仕事を別々の機能に分けています。それはあなたがそれらのケースをより簡単に処理できるようにします。スワップやバイナリ算術演算を実行するのに十分なデータがスタックにない場合に発生するスタックアンダーフローも忘れないでください。以下の例を参照してください。

(* just type aliases for convenience *) 
type stack = float list 
type binop = float -> float -> float 

(* helper function to prevent nested pattern matching below *) 
let denote_operation (op : oper) : binop = 
    match op with 
    | Plus -> (+.) 
    | Minus -> (-.) 
    | Times -> (*.) 
    | Divide -> (/.) 

(* This function executes only 1 instruction and 
    returns 'stack option', which may signal stack underflow *) 
let execute_instruction (i : instr) (st : stack) : stack option = 
    match i with 
    | Push f -> Some (f :: st) 
    | Swap -> 
     (match st with 
      | y :: x :: st' -> Some (x :: y :: st') 
      | _ -> None) 
    | Calculate op -> 
     (match st with 
      | y :: x :: st' -> Some ((denote_operation op x y) :: st') 
      | _ -> None) 

(* this function deals with a bunch of instructions *) 
let rec execute_program (il : instr list) (st : stack) : stack option = 
    match il with 
    | [] -> Some st 
    | i :: il' -> 
     match (execute_instruction i st) with 
     | None -> None 
     | Some st' -> execute_program il' st' 
関連する問題