小编Lea*_*erX的帖子

如何进行元组扩充

以下代码来自《F# 4.0 设计模式》第 5 章。

let a = 1,"car" 
type System.Tuple<'T1,'T2> with 
  member t.AsString() = 
    sprintf "[[%A]:[%A]]" t.Item1 t.Item2 
(a |> box :?> System.Tuple<int,string>).AsString()
Run Code Online (Sandbox Code Playgroud)

期望的输出是[[1]:["car"]]

但是,下面会出现一条红色波浪线AsString()。“字段、构造函数或成员‘AsString’未定义。也许您需要以下之一:ToString”

f#

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

递归函数中的空引用异常

下面的代码来自https://www.manning.com/books/real-world-function-programming的第8章

当我运行代码时,我在 testClientTree 中收到空引用异常。我检查了这本书的勘误表,但没有找到任何与此相关的内容。

type Client =
  { Name : string
    Income : int
    YearsInJob : int
    UsesCreditCard : bool
    CriminalRecord : bool }

let john = 
  { Name = "John Doe"  
    Income = 40000
    YearsInJob = 1
    UsesCreditCard = true
    CriminalRecord = false }

type ClientTests = 
  { Check   : Client -> bool
    Report : Client -> unit }

type QueryInfo =
  { Title : string
    Test : Client -> bool
    Positive : Decision
    Negative : Decision } …
Run Code Online (Sandbox Code Playgroud)

f#

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

对于相同模式,在 SML/NJ 中绑定不详尽的警告,但在 F# 中不绑定

下面的 SML/NJ 代码会生成“val Grove(whatTree) = glen”的绑定非详尽警告。F# 等效代码不会产生警告。为什么?

新泽西州标准 ML(32 位)v110.99.2 [构建时间:2021 年 9 月 28 日星期二 13:04:14]:

datatype tree = Oak|Elem|Maple|Spruce|Fir|Pine|Willow
datatype vegetable = Carrot|Zucchini|Tomato|Cucumber|Lettuce
datatype grain = Wheat|Oat|Barley|Maize
datatype plot = Grove of tree|Garden of vegetable|Field of grain|Vacant
val glen = Grove(Oak)
val Grove(whatTree) = glen
Run Code Online (Sandbox Code Playgroud)

F# 6.0.0 警告级别 5:

type Tree = Oak|Elem|Maple|Spruce|Fir|Pine|Willow
type Vegetable = Carrot|Zucchini|Tomato|Cucumber|Lettuce
type Grain = Wheat|Oat|Barley|Maize
type Plot = Grove of Tree|Garden of Vegetable|Field of Grain|Vacant
let glen = Grove(Oak)
let Grove(whatTree) = …
Run Code Online (Sandbox Code Playgroud)

f# sml smlnj

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

匹配表达式与模式匹配函数

我正在尝试将以下模式匹配函数转换为匹配表达式:

let reverse ls =
    let rec rev acc =
        function
        | h :: t -> rev (h :: acc) t
        | [] -> acc

    rev [] ls
Run Code Online (Sandbox Code Playgroud)

当我尝试转换为等效匹配表达式类型时,会发生不匹配错误:

let reverse ls =
    let rec rev acc =
        match acc with
        | h :: t -> rev (h :: acc) t
        | [] -> acc

    rev [] ls
Run Code Online (Sandbox Code Playgroud)

两者所需的输出是:

reverse [ 1; 2; 3 ]
// val it : int list = [3; 2; 1]
Run Code Online (Sandbox Code Playgroud)

f# pattern-matching

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

标签 统计

f# ×4

pattern-matching ×1

sml ×1

smlnj ×1