什么原因导致REPL打印函数签名而不是函数结果?

时间:2016-02-14 00:38:41

标签: f#

是什么原因导致REPL打印函数签名而不是函数结果?

我正在尝试执行以下行:

let email = Email "abc.com";;
email |> sendMessage |> ignore;;

代码如下

type PhoneNumber = 
    { CountryCode:int
      Number:string }

type ContactMethod =
    | Email of string
    | PhoneNumber of PhoneNumber

let sendMessage contact = function
    | Email _ -> printf "Sending message via email"
    | PhoneNumber phone -> printf "Sending message via phone"

// c. Create two values, one for the email address case and 
// one for the phone number case, and pass them to sendMessage.
let email = Email "abc.com";;
email |> sendMessage |> ignore;;

我得到以下结果:

type PhoneNumber =
  {CountryCode: int;
   Number: string;}
type ContactMethod =
  | Email of string
  | PhoneNumber of PhoneNumber
val sendMessage : contact:'a -> _arg1:ContactMethod -> unit
val email : ContactMethod = Email "abc.com"

>
val it : unit = ()

我期待这样的事情:

  

"通过电子邮件发送消息"

1 个答案:

答案 0 :(得分:6)

您的sendMessage函数需要两个参数:一个名为contact的无限制类型'a和一个匿名(_arg1在签名中){ {1}}。

当您向ContactMethod提供email时,您会获得一个sendMessage并返回ContactMethod的函数。然后你unit这个功能。

删除ignore参数(更惯用):

contact

或匹配(可能更容易理解):

let sendMessage = function
    | Email _ -> printf "Sending message via email"
    | PhoneNumber phone -> printf "Sending message via phone"

现在,let sendMessage contact = match contact with | Email _ -> printf "Sending message via email" | PhoneNumber phone -> printf "Sending message via phone" 的类型为sendMessage,您不再需要ContactMethod -> unit