代码之家  ›  专栏  ›  技术社区  ›  ozgur

基于递归函数和模式匹配的F#型推理

f#
  •  0
  • ozgur  · 技术社区  · 8 年前

    我有以下F代码

    let Operation (l:int list) =
        let A,B = l.[0], l.[1]
        if A > B then (-)
        else if A%2=0 && B%2=0 then (*)
        else (-)
    
    let m =
        function
        | [] -> []
        | x::rest -> rest
    
    let rec ops (l:int list) (opList:int->int->int list) =
        let operation = Operation l
        if l.Length = 0 then opList
        else ops (m l) (operation::opList)
    

    编译器在最后一行抱怨说

    此表达式应具有类型 '内景->内部->int list'但这里有类型 “名单”

    它是潜在的 (operation::opList) int -> int -> int opList的类型 int->int->int list

    1 回复  |  直到 8 年前
        1
  •  2
  •   Asik    8 年前

    int->int->int list
    

    相当于

    int->int->(int list)
    

    这是两个整数的函数,返回整数列表。

    你想写的是:

    (int->int->int) list
    

    这是返回int的两个int函数的列表。

    let Operation (l:int list) =
        let A,B = l.[0], l.[1]
        if A > B then (-)
        else if A%2=0 && B%2=0 then (*)
        else (-)
    
    let m =
        function
        | [] -> []
        | x::rest -> rest
    
    let rec ops (l:int list) (opList:(int->int->int) list) =
        let operation = Operation l
        if l.Length = 0 then opList
        else ops (m l) (operation::opList)