函数 returns string when bool is expected

Function returns string when bool is expected

这段代码有什么问题?

fun expd s:string = if size(s) > 0 then true else false;

我收到的错误:

- fun exnd s:string = if size(s) > a then true else false;
stdIn:657.1-837.8 Error: unbound variable or constructor: a
Error: right-hand-side of clause doesn't agree with function result type [tycon mismatch]
  expression:  bool
  result type: string

为什么会这样?

你需要在 s:string 周围加括号,因为现在 string 被解释为函数的输出类型而不是参数的类型 s:

fun expd (s:string) = if size(s) > 0 then true else false

顺便说一下,编译器可以在没有任何类型注释的情况下推断出这里的所有类型。尝试以下操作:

fun expd s = if size(s) > 0 then true else false

当然,您可以将此定义简化为:

fun expd s = size(s) > 0