gpt4 book ai didi

OCaml:如何正确处理 sum 类型?

转载 作者:行者123 更新时间:2023-12-03 18:25:54 25 4
gpt4 key购买 nike

假设我有以下代码:

type s = A of a | B of b


let foo (a:?) =

let bar (input:s) = match input with
| A a -> foo input
| B b -> ...

我的问题是我应该在 foo 的签名中填写问号,这样我就不需要(冗余)匹配语句了?或者有没有更好的模式来做到这一点?

最佳答案

如果您想避免重新匹配,我会看到 3 种解决方案:

  • 有功能foo只需取值构造函数的“有效载荷”A ,并重构 s 类型的值作为其输出(或与 bar 的输出类型匹配的任何其他类型)。
    # type a;;
    type a
    # type b;;
    type b


    # module Ex1 = struct

    type s = A of a | B of b


    let foo (a:a) = A a

    let bar (input:s) = match input with
    | A a -> foo a
    | B b -> (* ... *) input
    end;;

    module Ex1 :
    sig
    type s = A of a | B of b
    val foo : a -> s
    val bar : s -> s
    end
  • 使用多态变体:
    # module Ex2 = struct

    type s = [ `A of a | `B of b ]

    let foo (`A a) = `A a

    let bar (input:s) = match input with
    | `A _ as a -> foo a
    | `B b -> (* ... *) input
    end;;
    module Ex2 :
    sig
    type s = [ `A of a | `B of b ]
    val foo : [< `A of 'a ] -> [> `A of 'a ]
    val bar : s -> s
    end
  • 使用 GADT:
    # module Ex3 = struct

    type _ s =
    | A : a -> a s
    | B : b -> b s


    let foo (a: a s) : a s =
    match a with
    | A a -> A a

    let bar: type x. x s -> x s = fun input ->
    match input with
    | A _ as a -> foo a
    | B b -> (* ... *) input

    end;;
    module Ex3 :
    sig
    type _ s = A : a -> a s | B : b -> b s
    val foo : a s -> a s
    val bar : 'x s -> 'x s
    end
  • 关于OCaml:如何正确处理 sum 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29541186/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com