是什么原因导致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 = ()
我期待这样的事情:
"通过电子邮件发送消息"
答案 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
。