【问题标题】:using user-defined datatype as a type for a function argument使用用户定义的数据类型作为函数参数的类型
【发布时间】:2018-01-08 15:21:47
【问题描述】:

我定义了以下数据类型:

datatype Arguments
  = IntPair of int * int
  | RealTriple of real * real * real
  | StringSingle of string;

datatype OutputArgs = IntNum of int | RealNum of real | Str of string;

我尝试创建一个函数MultiFunc: Arguments -> OutputArgs:

fun MultiFunc(RealTriple (x, y, z)) : OutputArgs = RealNum ((x+y+z)/3.0)
  | MultiFunc(IntPair (x,y)) : OutputArgs = IntNum (x+y)
  | MultiFunc(StringSingle(s)) : OutputArgs = Str (implode(rev(explode(s))));

但是,当我调用 MultiFunc(1.0,2.0,3.0) 时,我收到以下错误:

stdIn:588.1-588.23 Error: operator and operand don't agree [tycon mismatch]
  operator domain: Arguments
  operand:         real * real * real
  in expression:
    MultiFunc (1.0,2.0,3.0)

即由于某种原因,它无法将输入参数识别为RealTriple

【问题讨论】:

    标签: sml smlnj


    【解决方案1】:
    MultiFunc(1.0,2.0,3.0)
    

    由于某种原因,它无法将输入参数识别为RealTriple

    这是因为输入不是RealTriple,而是实数的三元组 (real * real * real)。

    试试吧:

    - MultiFunc (RealTriple (1.0, 2.0, 3.0));
    > val it = RealNum 2.0 : OutputArgs
    

    这是我编写函数的方式:

    fun multiFunc (RealTriple (x, y, z)) = RealNum ((x+y+z)/3.0)
      | multiFunc (IntPair (x,y)) = IntNum (x+y)
      | multiFunc (StringSingle s) = Str (implode (rev (explode s)))
    

    通过让函数名称以小写字母开头,我在视觉上将它们与 RealTriple 之类的值构造函数区分开来。我不写: OutputArgs,而是让函数的类型被推断出来。而且我省略了像StringSingle(s)explode(s) 这样的多余括号:在许多编程语言中,函数调用必须有括号。在标准 ML 中,函数应用是通过将左侧的函数和右侧的参数并列并用空格分隔来实现的。所以f x 是在x 上调用的f,而(f x) y 是“无论f xy 上返回,用作函数。”

    【讨论】:

      【解决方案2】:

      您需要将您的三元组包装到相应的数据构造函数中,以向编译器解释您的意思是 Arguments 类型的东西,而不仅仅是实数的三元组:

      MultiFunc (RealTriple (1.0,2.0,3.0))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-22
        • 2023-03-28
        • 1970-01-01
        • 2022-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多