如何在F#中将函数直接应用于匹配表达式的值

问题描述

假设我有

let someFunction someVar =
  let x = 
    match someVar with
    | Value1 -> 10
    | Value2 -> 20
  anotherFunction x

有没有一种方法可以直接将“ anotherFunction”应用于匹配表达式的返回而无需使用辅助“ x”变量?

解决方法

是的,您可以直接应用它。

let someFunction someVar =
    anotherFunction( 
        match someVar with
        | Value1 -> 10
        | Value2 -> 20)

与F#中的大多数其他事情一样,匹配块是可以内联的表达式,如果您认为它可以改善代码的话。我不认为在这种情况下是可取的。

,

如果<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Beneficial Resources</title> <meta name="description" content=""> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="style.css"> <script type="text/javascript" src="src/material.js"></script> <script type="text/javascript" src="src/index.js"></script> </head> <body> <div class="form-container"> <form id="create-material-form"> <center> <h3>Add a new Resource</h3> <input id='input-name' type="text" name="name" value="" placeholder="Enter the Resource name" class="input-text"> <br><br> <textarea id='input-description' name="description" rows="8" cols="80" value="" placeholder="Enter the description of your Resource..."></textarea> <br><br> <input id="input-url" type="text" name="url" value="" placeholder="Enter the URL of your Resource..." class="input-text"> <br> <h3>What Category is your Resource?</h3> <select id="categories" name="categories"> <option value="1">Criminal Justice Reform</option> <option value="2">Bail Funds</option> <option value="3">Clothing</option> <option value="4">Organizations</option> <option value="5">Mutual Aid</option> <option value="6">Fundraisers</option> <option value="7">Petitions</option> <option value="8">Articles</option> <option value="9">Artists</option> <option value="10">Instagram</option> </select> <br> <input id="create-button" type="submit" name="submit" value="Add New Resource" class="submit"> </form> </center> <br> <br> </div> <div id="material-container"> </div> <div id="update-material"> </div> </body> </html> 的名称不重要,则可以使用函数组合来表示函数:

someVar

let someFunction = function | Value1 -> 10 | Value2 -> 20 >> anotherFunction 关键字是function的语法糖 fun x -> match x with...运算符采用一个函数并将其应用于另一个函数。

,

现有的答案向您展示了如何执行所需的操作,但是,如果我正在编写代码,我只会在比赛中重复函数调用-我更喜欢这样做,因为它是在其中放置“小表达式”(函数调用)一个“大表达式”(模式匹配)。反之,您最终会在一个小表达式内得到一个大表达式,这使语法不太清晰(在我看来)。

如果您还使用function来避免someVar,它将变成整齐的三层式:

let someFunction = function
  | Value1 -> anotherFunction 10
  | Value2 -> anotherFunction 20