F#Closure [英] F# Closure

查看:123
本文介绍了F#Closure的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都有一个体面的例子,最好是实用/有用的,他们可以发布演示这个概念?

Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?

推荐答案

由于许多原因,其中之一是减少辅助函数或值的大小。因此,不要使用随机垃圾来污染模块/命名空间,您可以将它们限定在必要的位置。

Closures can be used for any number of reasons, one of which is to reduce the sope of helper functions or values. So rather than polluting the module/namespace with random crap, you can scope them to just where they are necessary.

open System

let isStrongPassword password =

    let isLongEnough (str : string)   = str.Length > 10
    let containsNumber str =
        str |> Seq.tryfind (fun c -> Char.IsDigit(c)) |> Option.is_some
    let containsUpper str =
        str |> Seq.tryfind (fun c -> Char.IsUpper(c)) |> Option.is_some


    if isLongEnough password &&
       containsNumber password &&
       containsUpper password then
        true
    else
        false

编辑:
这是另一个捕获值并将它们带入内部范围而不作为参数传递的示例。

Here's another example that captures values and brings them into an inner scope without being passed as parameters.

#light

open System

let isPasswordStrongerThan myPassword yourPassword =

    let mineIsLongerThan    (x : string) = 
        (myPassword.Length > x.Length)

    let mineHasMoreNumsThan (x : string) =
        let numDigits (x : string) = 
            x 
            |> Seq.map (Char.IsDigit) 
            |> Seq.fold (+) 0
        (numDigits myPassword > numDigits x)

    if mineIsLongerThan yourPassword && mineHasMoreNumsThan yourPassword then
        true
    else
        false

'myPassword'用于所有内部函数,但它不作为参数传递。

In the example 'myPassword' is used in all the inner functions, but it wasn't passed as a parameter.

这篇关于F#Closure的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆