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) 这是这里的工作示例:
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,但它很糟糕并且不起作用。
我该怎么做?
有这个例子:
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# 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)