You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SML作业:如何让自定义datatype作为case匹配的返回值?

如何在SML函数中让自定义datatype作为case表达式的返回值

我需要写一个SML函数,类型是foo -> typ option,接收输入数据后返回匹配的自定义datatype类型。已知datatype定义如下:

datatype typ = typ1 
              | typ2
              | typ3
              (* ... *)
              | typn

我初步写的函数框架是:

hw_fun x =
  case x of 
    p1 => SOME typ1
   | p2 => SOME typ2
   (* ... *)
   | pn => SOME typn
   | _  => NONE 

但我不确定怎么让datatype作为case匹配的返回值,希望得到帮助。


你的函数框架本身是正确的,核心问题可能是缺少foo类型和匹配模式的具体定义。下面用实例演示完整实现方式:

实例1:foo为自定义datatype类型

先定义对应匹配的foo类型,再实现函数:

datatype foo = foo1 | foo2 | foo3 | other_foo
datatype typ = typ1 | typ2 | typ3

fun hw_fun x =
  case x of 
    foo1 => SOME typ1
   | foo2 => SOME typ2
   | foo3 => SOME typ3
   | _    => NONE 

实例2:foo为基础类型(如int)

如果输入是基础类型,只需把匹配模式换成对应类型的取值即可:

datatype typ = typ1 | typ2 | typ3

fun hw_fun x =
  case x of 
    1 => SOME typ1
   | 2 => SOME typ2
   | 3 => SOME typ3
   | _ => NONE 

关键说明

  • typ1、typ2等是你定义的typ datatype的构造器,它们本身就是typ类型的值,直接放入SOME中就能生成typ option类型的返回值。
  • 所有case分支的返回值类型必须统一:要么是SOME typX(属于typ option),要么是NONE(也属于typ option),完全符合foo -> typ option的函数类型要求。

内容的提问来源于stack exchange,提问作者Scentless Apprentice

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 10:17:10