我在Fable REPL 中编写了以下代码:
open Fable.Core
let inline sqr x = x * x
// Filters out `points` that are more than `radius` away
let inRadius radius points =
points
|> List.filter (fun (x, y) -> sqr x + sqr y <= sqr radius)
Run Code Online (Sandbox Code Playgroud)
输出 JavaScript 是:
import { filter } from "fable-library/List.js";
export function inRadius(radius, xs) {
return filter(function predicate(tupledArg) {
return tupledArg[0] * tupledArg[0] + tupledArg[1] * tupledArg[1] <= radius * radius;
}, xs);
}
Run Code Online (Sandbox Code Playgroud)
更优化的 JavaScript 是:
import { filter } from "fable-library/List.js";
export function inRadius(radius, xs) {
const radiusSquared = radius * radius;
return filter(function predicate(tupledArg) {
return tupledArg[0] * tupledArg[0] + tupledArg[1] * tupledArg[1] <= radiusSquared;
}, xs);
}
Run Code Online (Sandbox Code Playgroud)
(这只是可能应用的优化的一个例子,还有更多的可能性)
在 JavaScript 中,由于缺乏类型,很难安全地进行这种优化。但是,在原始 F# 代码中,我们知道 的类型,radius因此我们可以安全地进行此优化。对我来说,这似乎是 Fable 相对于 JavaScript 的一大优势。
然而,这样的优化需要在某处实际实施。
我希望 Fable 或任何其他转译器能够保留代码的结构。因此,您可以优化 F# 代码以仅计算一次 radius^2。
open Fable.Core
let inline sqr x = x * x
// Filters out `points` that are more than `radius` away
let inRadius radius =
let radiusSqr = sqr radius
List.filter (fun (x, y) -> sqr x + sqr y <= radiusSqr)
Run Code Online (Sandbox Code Playgroud)