【问题标题】:I was expecting a function to return bool, but "this expression was expected to have type 'int * int * string' but here has type 'string' "我期待一个函数返回布尔值,但是“这个表达式应该有类型'int * int * string'但这里有类型'string'”
【发布时间】:2021-02-10 08:31:09
【问题描述】:

我自己解决这个问题,四个小时后,我接近完成第 3.1.1 部分,但无法解释为什么我不能让它返回布尔值,特别是因为类似的函数很乐意做字符串连接。

(*
3.1 A time of day can be represented as a 
triple (hours, minutes, f) 
where f is either AM or PM – or as a record. 

Declare a function to test whether one time of day comes 
before another. 

For example, (11,59,"AM") comes before (1,15,"PM"). 

Make solutions with triples as well as with records. 

Declare the functions in infix notation.

Hansen, Michael R.; Rischel, Hans. 
Functional Programming Using F# (p. 66). 
Cambridge University Press. Kindle Edition. 
*)

type TimeOfDayTriple = int * int * string

let (<.) ((hour1, min1, pod1):TimeOfDayTriple) ((hour2, min2, pod2):TimeOfDayTriple) =
    true
//val ( <. ) : int * int * string -> int * int * string -> bool

let (<.) ((hour1, min1, pod1):TimeOfDayTriple) ((hour2, min2, pod2):TimeOfDayTriple) =
    (pod1, pod2)
//val ( <. ) : int * int * string -> int * int * string -> string * string

let (<.) ((hour1, min1, pod1):TimeOfDayTriple) ((hour2, min2, pod2):TimeOfDayTriple) =
    pod1 + pod2
val ( <. ) : int * int * string -> int * int * string -> string
    
let (<.) ((hour1, min1, pod1):TimeOfDayTriple) ((hour2, min2, pod2):TimeOfDayTriple) =
    pod1 < pod2;;
//Ch03.fsx(32,5): error FS0001: This expression was expected to have type
//    'int * int * string'    
//but here has type
//    'string'    

【问题讨论】:

  • 你有没有在上面的某个地方重新定义运算符(&lt;)

标签: f# tuples


【解决方案1】:

如 cmets 中所述,如果您不小心重新定义了 &lt; 运算符,您可能会收到此错误。我个人更喜欢避免使用自定义运算符,除非它们有特殊原因(例如解析器组合器,这是它们的既定领域)。

如果你只定义一个自定义函数compareTimes(可能在重新启动你的 REPL 之后),我认为你可以避免很多麻烦。

值得注意的是,您还可以在 F# 中使用运算符重载。这不是书本练习所要求的,但知道它可能会很好。要定义支持标准&lt;&gt; 等运算符的类型,您可以使用:

[<CustomComparison>]
type TimeOfDayTriple = 
  | TOD of int * int * string
  interface System.IComparable<TimeOfDayTriple> with
    member x.CompareTo(TOD(h2, m2, p2)) =
      let (TOD(h1, m1, p1)) = x
      // (implement comparison here)

【讨论】:

  • 我做到了。然后我尝试撤消它,但很有可能我没有成功清除环境。在 fsx 脚本模式下,有没有办法在不关闭 VisualStudio 的情况下清除 REPL 环境?
  • 我想你右击会出现重启或重置的选项
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2022-12-05
  • 1970-01-01
相关资源
最近更新 更多