小编Ale*_* 75的帖子

F# 是否可以识别 DU 的重叠并使用正确的重叠本身?

type GenericResult =
    | Ok
    | Error of string

type LoginResult =
    | Ok
    | UserNotFound
    | WrongPassword

let check something:GenericResult =
    match something with
    //| true -> Ok // error:This expression was expected to be of type "GenericREsult" but here has type "LoginResult"
    | true -> GenericResult.Ok // I'm forced to specify GenericResult.Ok
    | false -> Error "aargg!"

let checkLogin something:LoginResult =
    match something with
    | true -> Ok // here I don't need to specify the DU because …
Run Code Online (Sandbox Code Playgroud)

f# discriminated-union

2
推荐指数
1
解决办法
96
查看次数

F#在实现接口时从一个类型的另一个函数调用成员函数

这是这里的工作示例:

type MethodExample() = 

    // standalone method
    member this.AddOne x = 
        x + 1

    // calls another method
    member this.AddTwo x = 
        this.AddOne x |> this.AddOne
Run Code Online (Sandbox Code Playgroud)

这就是我想要做的:

type MethodExample() = 

    // standalone method
    member this.AddOne x = 
        x + 1

    // calls another method
    member this.AddTwo x = 
        this.AddOne x |> this.AddOne
Run Code Online (Sandbox Code Playgroud)

AddOne功能不可用,我也尝试将其向下转换为 MethodExample,但它很糟糕并且不起作用。

我该怎么做?

f#

1
推荐指数
1
解决办法
408
查看次数

F# | Array.map & Array.filter 一步到位(单功能)

有这个例子:

open FSharp.Data

let jsonStirng = @"[ 
    {""red"": 100, ""green"": 100, ""blue"": 100, ""alpha"": 1.0 },
    {""red"": 100, ""green"": 100, ""blue"": 100, ""alpha"": 0.5 },
    ]"

let getSolidColors jsonString =
    let getColor item = 
        if (item:JsonValue).["alpha"].AsDecimal() < 1m
        then Some( {R=item.["red"].AsInteger(); G=item.["green"].AsInteger(); B=item.["blue"].AsInteger()} )
        else None

    JsonValue.Parse(jsonString).AsArray() 
    |> Array.map getColor 
    |> Array.filter (fun x -> x.IsSome)
    |> Array.map (fun x -> x.Value)
Run Code Online (Sandbox Code Playgroud)

是否可以有一个函数在一次调用中生成地图和过滤器功能?
有点Array.mapfilter(不是因为我没有累加器而减少,或者这可能是解决方案?!)

或者,有一个替代实现(除了for循环)来避免使用中间Option和 3 Array 函数调用?

f#

1
推荐指数
1
解决办法
78
查看次数

F# - 将 LanguagePrimitives.GenericZero 与类构造函数上传递的值进行比较

按照此处的建议F# GreaterThanZero 传递 int 或decimal,我尝试value > LanguagePrimitives.GenericZero在类成员函数内部使用,但我找不到使用它的方法。
问题可能在于值是在类型构造函数中传递的,而不是传递给函数的。
请查看代码注释中的错误。

type IValidationCheck =   
    abstract member Validate: unit -> Result<unit, string>

type NumberIsPositiveCheck (property:string, value) =
    interface IValidationCheck with
        member (*inline*) this.Validate () =  //# does not allow me to use "inline"
            if value > LanguagePrimitives.GenericZero then Ok()  //# fail to compile: the type IComparable does not have a get_Zero operator
            else Error $"{property} must be greater than zero"
Run Code Online (Sandbox Code Playgroud)

f#

1
推荐指数
1
解决办法
53
查看次数

标签 统计

f# ×4

discriminated-union ×1