F# 是什么导致REPL打印函数签名而不是函数结果?
是什么导致REPL打印函数签名而不是函数结果? 我正在尝试执行以下行:F# 是什么导致REPL打印函数签名而不是函数结果?,f#,F#,是什么导致REPL打印函数签名而不是函数结果? 我正在尝试执行以下行: let email = Email "abc.com";; email |> sendMessage |> ignore;; 代码如下所示 type PhoneNumber = { CountryCode:int Number:string } type ContactMethod = | Email of string | PhoneNumber of PhoneNum
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 = ()
我期待这样的事情:
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 = ()
“通过电子邮件发送消息”
您的
sendMessage
函数接受两个参数:一个名为contact
的非限制类型'a
和一个匿名(\u arg1
在签名中)ContactMethod
当您将电子邮件
提供给发送消息
时,您将获得一个函数,该函数采用联系方法
并返回单位
。然后您可以忽略此函数
删除联系人
参数(更惯用):
或者匹配(可能更容易理解):
现在,
sendMessage
属于ContactMethod->unit
类型,您不再需要忽略。经验法则。如果您曾经不得不使用忽略并且不知道为什么,那么请仔细查看函数签名,很可能代码中潜伏着一个潜在的bug。我发现,ignore
在调用.NET代码时比F#函数时使用得更多,特别是当.NET代码有副作用时,例如,StringBuilder append
,您需要副作用,但不需要调用的结果。此外,如果您曾经使用按任意键继续
,那么您将使用控制台.ReadKey()|>忽略
;同样,你需要的是副作用,而不是结果。
let sendMessage contact =
match contact with
| Email _ -> printf "Sending message via email"
| PhoneNumber phone -> printf "Sending message via phone"