方便的F#代码段[关闭]


68

关于F#/功能片段,已经有两个 问题

但是,我在这里寻找的是有用的代码片段,一些可重用的“帮助程序”功能。或是您永远不会记得的晦涩但精巧的模式。

就像是:

open System.IO

let rec visitor dir filter= 
    seq { yield! Directory.GetFiles(dir, filter)
          for subdir in Directory.GetDirectories(dir) do 
              yield! visitor subdir filter} 

我想将其作为一种方便的参考页。因此,没有正确的答案,但希望有很多好的答案。

编辑Tomas Petricek创建了一个专门用于F#代码段的网站http://fssnip.net/


3
请使其成为社区Wiki。
布赖恩

完成后,我认为从一个正常的问题开始可能会为某些初步答案提供动力。
杰尔

Answers:


27

Perl样式正则表达式匹配

let (=~) input pattern =
    System.Text.RegularExpressions.Regex.IsMatch(input, pattern)

它使您可以使用let test = "monkey" =~ "monk.+"符号匹配文本。


27

中缀运算符

我是从http://sandersn.com/blog//index.php/2009/10/22/infix-function-trick-for-f获取的。请转到该页面以获取更多详细信息。

如果您知道Haskell,您可能会发现自己在F#中缺少固定糖:

// standard Haskell call has function first, then args just like F#. So obviously
// here there is a function that takes two strings: string -> string -> string 
startsWith "kevin" "k"

//Haskell infix operator via backQuotes. Sometimes makes a function read better.
"kevin" `startsWith` "K" 

尽管F#没有真正的“中缀”运算符,但可以通过管道和“后管道”(谁知道这样的事情?)来完成相同的任务

// F# 'infix' trick via pipelines
"kevin" |> startsWith <| "K"

10
+1:我不知道为什么,但是这让我感到恼火:)
朱丽叶

@朱丽叶我也是,但我想我知道为什么。记得一张照片。(不会在这里发布,它是NSFW)
显示名称

26

多行字符串

这是相当琐碎的,但这似乎是F#字符串的一个鲜为人知的功能。

let sql = "select a,b,c \
           from table \
           where a = 1"

这将产生:

val sql : string = "select a,b,c from table where a = 1"

当F#编译器在字符串文字中看到反斜杠后跟回车符时,它将删除所有内容,从反斜杠到下一行的第一个非空格字符。这使您可以排列多行字符串文字,而无需使用一串字符串串联。


7
只需添加一下,C#样式@“ string”也可以在F#中使用多行!
罗伯特·杰普森

2
仅供参考。您不再需要反斜杠。
Gagege 2015年

1
@Gagege-感谢您的提示,但是您能具体说明您来自哪个未来吗?我只是在F#3.1,VS 2013中尝试过,如果要从此版本的结果字符串中删除每行开头的空白,您仍然需要使用斜杠。
Joel Mueller

@Gagege没有反斜杠的多行字符串文字不会修剪字符串的换行符和前导空格(在F#4.0中进行测试)
Patrick McDonald

25

普通的回忆,由男人本人提供

let memoize f = 
  let cache = System.Collections.Generic.Dictionary<_,_>(HashIdentity.Structural)
  fun x ->
    let ok, res = cache.TryGetValue(x)
    if ok then res
    else let res = f x
         cache.[x] <- res
         res

使用此方法,您可以像这样进行缓存的读取器:

let cachedReader = memoize reader

9
您应该传递HashIdentity.Structural给,Dictionary否则它将在键上使用默认的.NET参考相等性,而不是F#的结构相等性。
JD 2010年

1
.NET喜欢通过引用比较值,而F#在结构上比较值(即根据它们的内容)。因此,根据.NET,两个数组[| 2 |]和[| 2 |]不相等,但根据F#相等。如果这些值在您的代码中显示为“ x”,它将对F#程序员产生意外的结果。当然,这在我的书中有描述。
JD

@Jon Harrop dict操作符会这样做吗?

1
@Ryan Riley:如果这样做,dict [[|1|], 2; [|1|], 4]您将得到一个与该键的单一绑定,该键[|1|]表明它确实在使用结构化哈希,是的。
JD

我将增强此记忆功能以使其更安全。如果将已区分的并集设置为具有空的编译表示形式,那么如果您要将该案例作为键插入,它将在运行时崩溃。因此,在保留之前,我会将密钥包装在选项类型中。
David Grenier

18

简单的文本文件读写

这些是微不足道的,但是使文件访问可传递:

open System.IO
let fileread f = File.ReadAllText(f)
let filewrite f s = File.WriteAllText(f, s)
let filereadlines f = File.ReadAllLines(f)
let filewritelines f ar = File.WriteAllLines(f, ar)

所以

let replace f (r:string) (s:string) = s.Replace(f, r)

"C:\\Test.txt" |>
    fileread |>
    replace "teh" "the" |>
    filewrite "C:\\Test.txt"

并将其与问题中引用的访问者结合起来:

let filereplace find repl path = 
    path |> fileread |> replace find repl |> filewrite path

let recurseReplace root filter find repl = 
    visitor root filter |> Seq.iter (filereplace find repl)

如果您希望能够读取“锁定”文件(例如,已经在Excel中打开的csv文件...),请更新“轻微改进”:

let safereadall f = 
   use fs = new FileStream(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
   use sr = new StreamReader(fs, System.Text.Encoding.Default)
   sr.ReadToEnd()

let split sep (s:string) = System.Text.RegularExpressions.Regex.Split(s, sep)

let fileread f = safereadall f
let filereadlines f = f |> safereadall |> split System.Environment.NewLine  

您可以通过管道传递File.ReadAllLines,它返回一个Array ...例如File.ReadAllLines(file)|> Array.map print_line
Russell 2010年

我想看看其中的一些用法示例,因为我还很新...专门针对"make file access pipeable:"
入门人员

对此感到困惑,因为所有这些File方法管道都很好,没有别名。例如“ C:\\ somefile.txt” |> File.ReadAllText
piers7 '16

@ piers7,只有带有一个参数的。给一个参数加上别名会使事情看起来不那么偏斜(对我而言)。
Benjol,2016年

18

对于性能密集型的东西,您需要检查null

let inline isNull o = System.Object.ReferenceEquals(o, null)
if isNull o then ... else ...

大约快20倍

if o = null then ... else ...

2
还要注意的是o = null需要Equality约束,如果你与仿制药的工作
Guvante

我的天啊!为什么会有如此大的差异?
显示名称

1
@SargeBorsch因为前者翻译成只是一个参考比较,而其他人则调用FSharp.Core.LanguagePrimitives.HashCompare.GenericEqualityIntrinsic,这是很多代码。
Asik

2
请注意,在F#4.0中,isNull它现在是标准的内联运算符,如果您不使用FSharpLint,它会发牢骚。
亚伯2015年

11

活动模式(又称“香蕉分割”)是一种非常方便的构造,可以让一个匹配多个正则表达式模式。这很像AWK,但是没有DFA的高性能,因为模式是按顺序匹配的,直到成功为止。

#light
open System
open System.Text.RegularExpressions

let (|Test|_|) pat s =
    if (new Regex(pat)).IsMatch(s)
    then Some()
    else None

let (|Match|_|) pat s =
    let opt = RegexOptions.None
    let re = new Regex(pat,opt)
    let m = re.Match(s)
    if m.Success
    then Some(m.Groups)
    else None

一些使用示例:

let HasIndefiniteArticle = function
        | Test "(?: |^)(a|an)(?: |$)" _ -> true
        | _ -> false

type Ast =
    | IntVal of string * int
    | StringVal of string * string
    | LineNo of int
    | Goto of int

let Parse = function
    | Match "^LET\s+([A-Z])\s*=\s*(\d+)$" g ->
        IntVal( g.[1].Value, Int32.Parse(g.[2].Value) )
    | Match "^LET\s+([A-Z]\$)\s*=\s*(.*)$" g ->
        StringVal( g.[1].Value, g.[2].Value )
    | Match "^(\d+)\s*:$" g ->
        LineNo( Int32.Parse(g.[1].Value) )
    | Match "^GOTO \s*(\d+)$" g ->
        Goto( Int32.Parse(g.[1].Value) )
    | s -> failwithf "Unexpected statement: %s" s

8

也许单子

type maybeBuilder() =
    member this.Bind(v, f) =
        match v with
        | None -> None
        | Some(x) -> f x
    member this.Delay(f) = f()
    member this.Return(v) = Some v

let maybe = maybeBuilder()

这是针对初学者的Monad的简短介绍。


1
我在github.com/panesofglass/FSharp.Monad上有一个完整的库;其中许多来自Matthew Podwysocki的系列。

8

期权销售经营者

我想要一个defaultArg函数的版本,其语法更接近C#null-coalescing运算符??。这使我可以使用非常简洁的语法从Option中获取值,同时提供默认值。

/// Option-coalescing operator - this is like the C# ?? operator, but works with 
/// the Option type.
/// Warning: Unlike the C# ?? operator, the second parameter will always be 
/// evaluated.
/// Example: let foo = someOption |? default
let inline (|?) value defaultValue =
    defaultArg value defaultValue

/// Option-coalescing operator with delayed evaluation. The other version of 
/// this operator always evaluates the default value expression. If you only 
/// want to create the default value when needed, use this operator and pass
/// in a function that creates the default.
/// Example: let foo = someOption |?! (fun () -> new Default())
let inline (|?!) value f =
    match value with Some x -> x | None -> f()

1
整洁-延迟评估版本的另一种选择是使用Lazy<'a>第二个参数代替unit -> 'a,然后该示例如下所示someOption |?! lazy(new Default())
Stephen Swensen

@Stephen-好点。我实际上更喜欢那个。
乔尔·穆勒

8

使用FloatWithMeasure功能http://msdn.microsoft.com/en-us/library/ee806527(VS.100).aspx无法处理单位的功能“统一”

let unitize (f:float -> float) (v:float<'u>) =
  LanguagePrimitives.FloatWithMeasure<'u> (f (float v))

例:

[<Measure>] type m
[<Measure>] type kg

let unitize (f:float -> float) (v:float<'u>) =
  LanguagePrimitives.FloatWithMeasure<'u> (f (float v))

//this function doesn't take units
let badinc a = a + 1.

//this one does!
let goodinc v = unitize badinc v

goodinc 3.<m>
goodinc 3.<kg>

旧版本

let unitize (f:float -> float) (v:float<'u>) =
  let unit = box 1. :?> float<'u>
  unit * (f (v/unit))

转换为kvb


7

比例/比率功能构建器

再次,琐碎但方便。

//returns a function which will convert from a1-a2 range to b1-b2 range
let scale (a1:float<'u>, a2:float<'u>) (b1:float<'v>,b2:float<'v>) = 
    let m = (b2 - b1)/(a2 - a1) //gradient of line (evaluated once only..)
    (fun a -> b1 + m * (a - a1))

例:

[<Measure>] type m
[<Measure>] type px

let screenSize = (0.<px>, 300.<px>)
let displayRange = (100.<m>, 200.<m>)
let scaleToScreen = scale displayRange screenSize

scaleToScreen 120.<m> //-> 60.<px>

6

转置列表(请参阅Jomo Fisher的博客

///Given list of 'rows', returns list of 'columns' 
let rec transpose lst =
    match lst with
    | (_::_)::_ -> List.map List.head lst :: transpose (List.map List.tail lst)
    | _         -> []

transpose [[1;2;3];[4;5;6];[7;8;9]] // returns [[1;4;7];[2;5;8];[3;6;9]]

这是一个尾递归版本,它(根据我的粗略分析)稍慢一些,但具有以下优点:当内部列表的长度超过10000个元素(在我的机器上)时,不会引发堆栈溢出:

let transposeTR lst =
  let rec inner acc lst = 
    match lst with
    | (_::_)::_ -> inner (List.map List.head lst :: acc) (List.map List.tail lst)
    | _         -> List.rev acc
  inner [] lst

如果我很聪明,我会尝试使用异步将其并行化...


6

F#地图<-> C#字典

(我知道,System.Collections.Generic.Dictionary并不是真正的“ C#”字典)

C#至F#

(dic :> seq<_>)                        //cast to seq of KeyValuePair
    |> Seq.map (|KeyValue|)            //convert KeyValuePairs to tuples
    |> Map.ofSeq                       //convert to Map

(来自Brian,这里有Mauricio提出的改进,在下面的评论中。这(|KeyValue|)是一种用于匹配KeyValuePair的有效模式-来自FSharp.Core-等效于(fun kvp -> kvp.Key, kvp.Value)

有趣的选择

要获得所有不可变的优点,但要使用Dictionary的O(1)查找速度,可以使用dict运算符,该运算符将返回一个不变的IDictionary(请参阅此问题)。

我目前看不到使用此方法直接转换字典的方法,除了

(dic :> seq<_>)                        //cast to seq of KeyValuePair
    |> (fun kvp -> kvp.Key, kvp.Value) //convert KeyValuePairs to tuples
    |> dict                            //convert to immutable IDictionary

从F#到C#

let dic = Dictionary()
map |> Map.iter (fun k t -> dic.Add(k, t))
dic

奇怪的是FSI会将类型报告为(例如):

val it : Dictionary<string,int> = dict [("a",1);("b",2)]

但是如果您反馈dict [("a",1);("b",2)],FSI报告

IDictionary<string,int> = seq[[a,1] {Key = "a"; Value = 1; } ...

2
我认为Seq.map将KeyValues转换为元组时会丢失。此外,您还可以使用(|KeyValue|),而不是fun kvp -> kvp.Key,kvp.Value
毛里西奥·雅伯

@Mauricio,位置很好,而且很有趣(|KeyValue|)-这几乎是值得的!
Benjol

5

树排序/将树展平到列表中

我有以下二进制树:

             ___ 77 _
            /        \
   ______ 47 __       99
  /            \
21 _          54
    \        /  \
      43    53  74
     /
    39
   /
  32

表示如下:

type 'a tree =
    | Node of 'a tree * 'a * 'a tree
    | Nil

let myTree =
    Node
      (Node
         (Node (Nil,21,Node (Node (Node (Nil,32,Nil),39,Nil),43,Nil)),47,
          Node (Node (Nil,53,Nil),54,Node (Nil,74,Nil))),77,Node (Nil,99,Nil))

扁平化树的简单方法是:

let rec flatten = function
    | Nil -> []
    | Node(l, a, r) -> flatten l @ a::flatten r

这不是尾递归,我相信@运算符会导致它是O(n log n)或O(n ^ 2)(带有不平衡的二叉树)。经过一些调整,我想到了这个尾递归的O(n)版本:

let flatten2 t =
    let rec loop acc c = function
        | Nil -> c acc
        | Node(l, a, r) ->
            loop acc (fun acc' -> loop (a::acc') c l) r
    loop [] (fun x -> x) t

这是fsi的输出:

> flatten2 myTree;;
val it : int list = [21; 32; 39; 43; 47; 53; 54; 74; 77; 99]

@Benjol:我不确定flatten2之类的例子是否支持或反对延续传递风格;)
朱丽叶

@Benjol将尾递归版本视为将数据存储在闭包中而不是堆栈中。如果您查看“(fun acc'->循环(a :: acc')cl)”,则仅将acc'传递给函数,因此F#必须以某种方式保存a,c,l,以便将来在评估函数时使用。
gradbot

您可能会发现,使用连续传递样式或为左递归明确地堆积堆栈或父节点,可以更轻松地在树上书写折叠。然后用flatten倍数表示为fold cons [] xs
JD 2010年

我更喜欢该方案的版本(apply append lst1 lst2 lst3)。虽然不是递归的。
leppie

5

LINQ到XML的助手

namespace System.Xml.Linq

// hide warning about op_Explicit
#nowarn "77"

[<AutoOpen>]
module XmlUtils =

    /// Converts a string to an XName.
    let xn = XName.op_Implicit
    /// Converts a string to an XNamespace.
    let xmlns = XNamespace.op_Implicit

    /// Gets the string value of any XObject subclass that has a Value property.
    let inline xstr (x : ^a when ^a :> XObject) =
        (^a : (member get_Value : unit -> string) x)

    /// Gets a strongly-typed value from any XObject subclass, provided that
    /// an explicit conversion to the output type has been defined.
    /// (Many explicit conversions are defined on XElement and XAttribute)
    /// Example: let value:int = xval foo
    let inline xval (x : ^a when ^a :> XObject) : ^b = 
        ((^a or ^b) : (static member op_Explicit : ^a -> ^b) x) 

    /// Dynamic lookup operator for getting an attribute value from an XElement.
    /// Returns a string option, set to None if the attribute was not present.
    /// Example: let value = foo?href
    /// Example with default: let value = defaultArg foo?Name "<Unknown>"
    let (?) (el:XElement) (name:string) =
        match el.Attribute(xn name) with
        | null -> None
        | att  -> Some(att.Value)

    /// Dynamic operator for setting an attribute on an XElement.
    /// Example: foo?href <- "http://www.foo.com/"
    let (?<-) (el:XElement) (name:string) (value:obj) =
        el.SetAttributeValue(xn name, value)

感谢这些。我已经看过Tomas会抛出?型运算符,但是我不明白的是如何将“按代码命名”神奇地转换为“按字符串命名”(为什么不必这样做foo?"href"?) 。?<-中间的“分离”是什么魔法呢?我的无知暴露在所有人面前
Benjol

2
@Benjol-这是一个编译器技巧。F#编译器将?运算符的定义转换为称为静态方法的静态方法op_Dynamic,该方法采用字符串参数。然后,它将?运算符的使用转化为对该方法的调用,问号后的部分为字符串参数。因此,在运行时,它们都是静态类型的,而根本不是动态的,它只是提供了一些不错的简洁语法,您可以用来定义其行为。与?<-操作员相同的原理。
乔尔·穆勒

4

好的,这与代码片段无关,但我一直忘记这一点:

如果您在交互式窗口中,请单击F7以跳回到代码窗口(无需取消选择刚刚运行的代码...)

从代码窗口转到F#窗口(并同时打开F#窗口)是 Ctrl Alt F

(除非CodeRush偷走了您的绑定...)


FWIW,您可以更改Ctrl + Alt + F CodeRush绑定,以使其仅以DXCore支持的语言(即不支持F#)运行。为此,请执行以下操作:找到“ DevExpress \ CodeRush \ Options”菜单...在左侧选择“ IDE \快捷方式” ...找到“导航” \ Ctrl + Alt + F快捷方式。突出显示此内容,然后在右侧选中“支持语言\活动语言”上下文项。单击“确定”,此快捷方式应开始按照您想要的方式工作。
罗里·贝克尔

4

数组的加权和

根据权重的[k数组]计算数字的[n数组的k数组]的加权[n数组]总和

(从这个问题kvb答案复制)

给定这些数组

let weights = [|0.6;0.3;0.1|]

let arrs = [| [|0.0453;0.065345;0.07566;1.562;356.6|] ; 
           [|0.0873;0.075565;0.07666;1.562222;3.66|] ; 
           [|0.06753;0.075675;0.04566;1.452;3.4556|] |]

考虑到数组的两个维度都是可变的,我们需要一个加权和(按列)。

Array.map2 (fun w -> Array.map ((*) w)) weights arrs 
|> Array.reduce (Array.map2 (+))

第一行:将第一个Array.map2函数部分应用到权重会产生一个新函数(Array.map((*)weight))(针对每个权重)应用于arr中的每个数组。

第二行:Array.reduce类似于fold,不同之处在于它从第二个值开始并将第一个用作初始“状态”。在这种情况下,每个值都是我们数组数组的“一行”。因此,在前两行应用Array.map2(+)意味着我们对前两个数组求和,这给我们留下了一个新数组,然后我们将(Array.reduce)再次求和到下一个(在本例中为最后一个)数组。

结果:

[|0.060123; 0.069444; 0.07296; 1.5510666; 215.40356|]

这让我震惊,因为我从来没有想过可以映射两个不同的列表。
Benjol 2010年

4

性能测试

(在此处找到并已更新为F#的最新版本)

open System
open System.Diagnostics 
module PerformanceTesting =
    let Time func =
        let stopwatch = new Stopwatch()
        stopwatch.Start()
        func()
        stopwatch.Stop()
        stopwatch.Elapsed.TotalMilliseconds

    let GetAverageTime timesToRun func = 
        Seq.initInfinite (fun _ -> (Time func))
        |> Seq.take timesToRun
        |> Seq.average

    let TimeOperation timesToRun =
        GC.Collect()
        GetAverageTime timesToRun

    let TimeOperations funcsWithName =
        let randomizer = new Random(int DateTime.Now.Ticks)
        funcsWithName
        |> Seq.sortBy (fun _ -> randomizer.Next())
        |> Seq.map (fun (name, func) -> name, (TimeOperation 100000 func))

    let TimeOperationsAFewTimes funcsWithName =
        Seq.initInfinite (fun _ -> (TimeOperations funcsWithName))
        |> Seq.take 50
        |> Seq.concat
        |> Seq.groupBy fst
        |> Seq.map (fun (name, individualResults) -> name, (individualResults |> Seq.map snd |> Seq.average))

FWIW,stopwatch.Elapsed.TotalSeconds更准确。
JD

IIRC,其准确度约为100倍。
JD

3

F#,DataReaders的DataSetExtensions

System.Data.DataSetExtensions.dll增加了将aDataTable视为IEnumerable<DataRow>以及DBNull通过支持System.Nullable优雅地处理单个单元格的值的功能。例如,在C#中,我们可以获取包含空值的整数列的值,并使用DBNull非常简洁的语法指定应默认为零:

var total = myDataTable.AsEnumerable()
                       .Select(row => row.Field<int?>("MyColumn") ?? 0)
                       .Sum();

但是,在两个方面缺少DataSetExtensions。首先,它不支持IDataReader,其次,它不支持F#option类型。以下代码可同时实现这两个功能-允许将anIDataReader视为seq<IDataRecord>,并且可以从阅读器或数据集中拆箱值,并支持F#选项或System.Nullable。在另一个答案中与option-coalescing运算符结合使用,使用DataReader时,可以使用以下代码:

let total =
    myReader.AsSeq
    |> Seq.map (fun row -> row.Field<int option>("MyColumn") |? 0)
    |> Seq.sum

也许一种更惯用的F#忽略数据库空值的方式可能是...

let total =
    myReader.AsSeq
    |> Seq.choose (fun row -> row.Field<int option>("MyColumn"))
    |> Seq.sum

此外,下面定义的扩展方法可用于F#和C#/ VB。

open System
open System.Data
open System.Reflection
open System.Runtime.CompilerServices
open Microsoft.FSharp.Collections

/// Ported from System.Data.DatasetExtensions.dll to add support for the Option type.
[<AbstractClass; Sealed>]
type private UnboxT<'a> private () =

    // This class generates a converter function based on the desired output type,
    // and then re-uses the converter function forever. Because the class itself is generic,
    // different output types get different cached converter functions.

    static let referenceField (value:obj) =
        if value = null || DBNull.Value.Equals(value) then
            Unchecked.defaultof<'a>
        else
            unbox value

    static let valueField (value:obj) =
        if value = null || DBNull.Value.Equals(value) then
            raise <| InvalidCastException("Null cannot be converted to " + typeof<'a>.Name)
        else
            unbox value

    static let makeConverter (target:Type) methodName =
        Delegate.CreateDelegate(typeof<Converter<obj,'a>>,
                                typeof<UnboxT<'a>>
                                    .GetMethod(methodName, BindingFlags.NonPublic ||| BindingFlags.Static)
                                    .MakeGenericMethod([| target.GetGenericArguments().[0] |]))
        |> unbox<Converter<obj,'a>>
        |> FSharpFunc.FromConverter

    static let unboxFn =
        let theType = typeof<'a>
        if theType.IsGenericType && not theType.IsGenericTypeDefinition then
            let genericType = theType.GetGenericTypeDefinition()
            if typedefof<Nullable<_>> = genericType then
                makeConverter theType "NullableField"
            elif typedefof<option<_>> = genericType then
                makeConverter theType "OptionField"
            else
                invalidOp "The only generic types supported are Option<T> and Nullable<T>."
        elif theType.IsValueType then
            valueField
        else
            referenceField

    static member private NullableField<'b when 'b : struct and 'b :> ValueType and 'b:(new:unit -> 'b)> (value:obj) =
        if value = null || DBNull.Value.Equals(value) then
            Nullable<_>()
        else
            Nullable<_>(unbox<'b> value)

    static member private OptionField<'b> (value:obj) =
        if value = null || DBNull.Value.Equals(value) then
            None
        else
            Some(unbox<'b> value)

    static member inline Unbox =
        unboxFn

/// F# data-related extension methods.
[<AutoOpen>]
module FsDataEx =

    type System.Data.IDataReader with

        /// Exposes a reader's current result set as seq<IDataRecord>.
        /// Reader is closed when sequence is fully enumerated.
        member this.AsSeq =
            seq { use reader = this
                  while reader.Read() do yield reader :> IDataRecord }

        /// Exposes all result sets in a reader as seq<seq<IDataRecord>>.
        /// Reader is closed when sequence is fully enumerated.
        member this.AsMultiSeq =
            let rowSeq (reader:IDataReader)  =
                seq { while reader.Read() do yield reader :> IDataRecord }
            seq {
                use reader = this
                yield rowSeq reader
                while reader.NextResult() do
                    yield rowSeq reader
            }

        /// Populates a new DataSet with the contents of the reader. Closes the reader after completion.
        member this.ToDataSet () =
            use reader = this
            let dataSet = new DataSet(RemotingFormat=SerializationFormat.Binary, EnforceConstraints=false)
            dataSet.Load(reader, LoadOption.OverwriteChanges, [| "" |])
            dataSet

    type System.Data.IDataRecord with

        /// Gets a value from the record by name. 
        /// DBNull and null are returned as the default value for the type.
        /// Supports both nullable and option types.
        member this.Field<'a> (fieldName:string) =
            this.[fieldName] |> UnboxT<'a>.Unbox

        /// Gets a value from the record by column index. 
        /// DBNull and null are returned as the default value for the type.
        /// Supports both nullable and option types.
        member this.Field<'a> (ordinal:int) =
            this.GetValue(ordinal) |> UnboxT<'a>.Unbox

    type System.Data.DataRow with

        /// Identical to the Field method from DatasetExtensions, but supports the F# Option type.
        member this.Field2<'a> (columnName:string) =
            this.[columnName] |> UnboxT<'a>.Unbox

        /// Identical to the Field method from DatasetExtensions, but supports the F# Option type.
        member this.Field2<'a> (columnIndex:int) =
            this.[columnIndex] |> UnboxT<'a>.Unbox

        /// Identical to the Field method from DatasetExtensions, but supports the F# Option type.
        member this.Field2<'a> (column:DataColumn) =
            this.[column] |> UnboxT<'a>.Unbox

        /// Identical to the Field method from DatasetExtensions, but supports the F# Option type.
        member this.Field2<'a> (columnName:string, version:DataRowVersion) =
            this.[columnName, version] |> UnboxT<'a>.Unbox

        /// Identical to the Field method from DatasetExtensions, but supports the F# Option type.
        member this.Field2<'a> (columnIndex:int, version:DataRowVersion) =
            this.[columnIndex, version] |> UnboxT<'a>.Unbox

        /// Identical to the Field method from DatasetExtensions, but supports the F# Option type.
        member this.Field2<'a> (column:DataColumn, version:DataRowVersion) =
            this.[column, version] |> UnboxT<'a>.Unbox


/// C# data-related extension methods.
[<Extension; AbstractClass; Sealed>]
type CsDataEx private () =

    /// Populates a new DataSet with the contents of the reader. Closes the reader after completion.
    [<Extension>]    
    static member ToDataSet(this:IDataReader) =
        this.ToDataSet()

    /// Exposes a reader's current result set as IEnumerable{IDataRecord}.
    /// Reader is closed when sequence is fully enumerated.
    [<Extension>]
    static member AsEnumerable(this:IDataReader) =
        this.AsSeq

    /// Exposes all result sets in a reader as IEnumerable{IEnumerable{IDataRecord}}.
    /// Reader is closed when sequence is fully enumerated.
    [<Extension>]
    static member AsMultipleEnumerable(this:IDataReader) =
        this.AsMultiSeq

    /// Gets a value from the record by name. 
    /// DBNull and null are returned as the default value for the type.
    /// Supports both nullable and option types.
    [<Extension>]
    static member Field<'T> (this:IDataRecord, fieldName:string) =
        this.Field<'T>(fieldName)

    /// Gets a value from the record by column index. 
    /// DBNull and null are returned as the default value for the type.
    /// Supports both nullable and option types.
    [<Extension>]
    static member Field<'T> (this:IDataRecord, ordinal:int) =
        this.Field<'T>(ordinal)

2

处理参数在命令行应用程序中:

//We assume that the actual meat is already defined in function 
//    DoStuff (string -> string -> string -> unit)
let defaultOutOption = "N"
let defaultUsageOption = "Y"

let usage =  
      "Scans a folder for and outputs results.\n" +
      "Usage:\n\t MyApplication.exe FolderPath [IncludeSubfolders (Y/N) : default=" + 
      defaultUsageOption + "] [OutputToFile (Y/N): default=" + defaultOutOption + "]"

let HandlArgs arr = 
    match arr with
        | [|d;u;o|] -> DoStuff d u o
        | [|d;u|] -> DoStuff d u defaultOutOption 
        | [|d|] -> DoStuff d defaultUsageOption defaultOutOption 
        | _ ->  
            printf "%s" usage
            Console.ReadLine() |> ignore

[<EntryPoint>]
let main (args : string array) = 
    args |> HandlArgs
    0

(我对这项技术的模糊记忆是受罗伯特·皮克林启发,但现在找不到参考)


PowerPack的已经自带了一个漂亮的CMDLINE ARG解析器:laurent.le-brun.eu/site/index.php/2010/06/08/...
毛里西奥·雅伯

2

方便的缓存功能,可保留max (key,reader(key))在字典中并使用SortedList来跟踪MRU键

let Cache (reader: 'key -> 'value) max = 
        let cache = new Dictionary<'key,LinkedListNode<'key * 'value>>()
        let keys = new LinkedList<'key * 'value>()

        fun (key : 'key) -> ( 
                              let found, value = cache.TryGetValue key
                              match found with
                              |true ->
                                  keys.Remove value
                                  keys.AddFirst value |> ignore
                                  (snd value.Value)

                              |false -> 
                                  let newValue = key,reader key
                                  let node = keys.AddFirst newValue
                                  cache.[key] <- node

                                  if (keys.Count > max) then
                                    let lastNode = keys.Last
                                    cache.Remove (fst lastNode.Value) |> ignore
                                    keys.RemoveLast() |> ignore

                                  (snd newValue))

抱歉,我的意思是MRU(最近使用最多)。将阅读器想象成一种访问远程数据库或Web服务甚至是非常繁重的计算的缓慢查找功能。
卡·马丁内蒂

是的,我可以看到缓存的用途,而不是“修剪”它。让我想知道我是否不应该在其中添加
摘要

2

创建XElement

没什么了不起的,但是我一直被XNames的隐式转换所吸引:

#r "System.Xml.Linq.dll"
open System.Xml.Linq

//No! ("type string not compatible with XName")
//let el = new XElement("MyElement", "text") 

//better
let xn s = XName.op_Implicit s
let el = new XElement(xn "MyElement", "text")

//or even
let xEl s o = new XElement(xn s, o)
let el = xEl "MyElement" "text"

该转换是.Net的一部分,它具有隐式的cast(String,XElement)重载。因此,任何支持强制重载的.Net语言都支持此功能。不错的功能。
Dykam'2

@Dykam,恐怕这是一个有点复杂多了:codebetter.com/blogs/matthew.podwysocki/archive/2009/06/11/...
Benjol

嗯,解释了这个功能。但是在扫描时,我无法找出为什么F#不支持转换运算符。
Dykam

2

成对和成对

我一直希望Seq.pairwise给我[(1,2);(3; 4)]而不是[(1,2);(2,3);(3,4)]。鉴于List中都不存在,并且我都需要,所以这里有代码供将来参考。我认为它们是尾递归的

//converts to 'windowed tuples' ([1;2;3;4;5] -> [(1,2);(2,3);(3,4);(4,5)])
let pairwise lst = 
    let rec loop prev rem acc = 
       match rem with
       | hd::tl -> loop hd tl ((prev,hd)::acc)
       | _ -> List.rev acc
    loop (List.head lst) (List.tail lst) []

//converts to 'paged tuples' ([1;2;3;4;5;6] -> [(1,2);(3,4);(5,6)])    
let pairs lst = 
    let rec loop rem acc = 
       match rem with
       | l::r::tl -> loop tl ((l,r)::acc)
       | l::[] -> failwith "odd-numbered list" 
       | _ -> List.rev acc
    loop lst []

1

天真的CSV阅读器(即不会处理任何令人讨厌的内容)

(在这里使用filereadlines和List.transpose从其他答案)

///Given a file path, returns a List of row lists
let ReadCSV = 
        filereadlines
            >> Array.map ( fun line -> line.Split([|',';';'|]) |> List.ofArray )
            >> Array.toList

///takes list of col ids and list of rows, 
///   returns array of columns (in requested order)
let GetColumns cols rows = 
    //Create filter
    let pick cols (row:list<'a>) = List.map (fun i -> row.[i]) cols

    rows 
        |> transpose //change list of rows to list of columns
        |> pick cols      //pick out the columns we want
        |> Array.ofList  //an array output is easier to index for user

"C:\MySampleCSV"
   |> ReadCSV
   |> List.tail //skip header line
   |> GetColumns [0;3;1]  //reorder columns as well, if needs be.

1

日期范围

之间的日期的简单实用的名单fromDatetoDate

let getDateRange  fromDate toDate  =

    let rec dates (fromDate:System.DateTime) (toDate:System.DateTime) = 
        seq {
            if fromDate <= toDate then 
                yield fromDate
                yield! dates (fromDate.AddDays(1.0)) toDate
            }

    dates fromDate toDate
    |> List.ofSeq

1

将代码切换到sql

比这个清单上的大多数都更琐碎,但仍然很方便:

我总是在开发过程中将sql移入和移出代码,以将其移至sql环境。例:

let sql = "select a,b,c "
    + "from table "
    + "where a = 1"

需要“剥离”至:

select a,b,c
from table
where a = 1

保持格式。剥离sql编辑器的代码符号,然后在我计算出sql以后再次手动放回它们是很痛苦的。这两个函数将sql从代码来回切换为剥离:

// reads the file with the code quoted sql, strips code symbols, dumps to FSI
let stripForSql fileName = 
    File.ReadAllText(fileName)
    |> (fun s -> Regex.Replace(s, "\+(\s*)\"", "")) 
    |> (fun s -> s.Replace("\"", ""))
    |> (fun s -> Regex.Replace(s, ";$", "")) // end of line semicolons
    |> (fun s -> Regex.Replace(s, "//.+", "")) // get rid of any comments
    |> (fun s -> printfn "%s" s)

然后,当您准备将其放回代码源文件中时:

let prepFromSql fileName = 
    File.ReadAllText(fileName)
    |> (fun s -> Regex.Replace(s, @"\r\n", " \"\r\n+\"")) // matches newline 
    |> (fun s -> Regex.Replace(s, @"\A", " \"")) 
    |> (fun s -> Regex.Replace(s, @"\z", " \"")) 
    |> (fun s -> printfn "%s" s)

摆脱输入文件,但甚至不能开始神交如何做到这一点。任何人?

编辑:

我想出了如何通过添加Windows窗体对话框输入/输出来消除这些功能的文件需求。要显示的代码太多,但是对于那些想做这样的事情的人,这就是我解决的方法。


还没有一个编译器可以解决您的最后一个问题,但是我会用它们来使您的管道更漂亮:let replace f r (s:string) = s.Replace(f,r)let regreplace p r s = Regex.Replace(s, p, r)
unested

1

Pascal的Triangle(嘿,有人可能会觉得有用)

所以我们想创建一个类似这样的东西:

       1
      1 1
     1 2 1
    1 3 3 1
   1 4 6 4 1

很简单:

let rec next = function
    | [] -> []
    | x::y::xs -> (x + y)::next (y::xs)
    | x::xs -> x::next xs

let pascal n =
    seq { 1 .. n }
    |> List.scan (fun acc _ -> next (0::acc) ) [1]

next函数返回一个新列表,其中每个项目[i] =项目[i] +项目[i + 1]。

这是fsi的输出:

> pascal 10 |> Seq.iter (printfn "%A");;
[1]
[1; 1]
[1; 2; 1]
[1; 3; 3; 1]
[1; 4; 6; 4; 1]
[1; 5; 10; 10; 5; 1]
[1; 6; 15; 20; 15; 6; 1]
[1; 7; 21; 35; 35; 21; 7; 1]
[1; 8; 28; 56; 70; 56; 28; 8; 1]
[1; 9; 36; 84; 126; 126; 84; 36; 9; 1]
[1; 10; 45; 120; 210; 252; 210; 120; 45; 10; 1]

对于喜欢冒险的人,这里有一个尾递归版本:

let rec next2 cont = function
    | [] -> cont []
    | x::y::xs -> next2 (fun l -> cont <| (x + y)::l ) <| y::xs
    | x::xs -> next2 (fun l -> cont <| x::l ) <| xs

let pascal2 n =
    set { 1 .. n }
    |> Seq.scan (fun acc _ -> next2 id <| 0::acc)) [1]


现在,您只需要打印以下内容即可:) stackoverflow.com/questions/1733311/pretty-print-a-tree
Benjol,2009年

0

整理清单

如果您有这样的事情:

let listList = [[1;2;3;];[4;5;6]] 

并想将其“展平”到一个单一的列表,因此结果如下所示:

[1;2;3;4;5;6]

可以这样完成:

let flatten (l: 'a list list) =
    seq {
            yield List.head (List.head l) 
            for a in l do yield! (Seq.skip 1 a) 
        } 

    |> List.ofSeq

6
非常抱歉,但是我认为已经存在:它是List.concat。(这一直在我身上发生-编写一个函数,然后发现它已经存在!)。有趣的是,看看是否有一个函数可以“递归”地执行此操作(例如[[[1;2;3;];[4;5;6]];[[1;2;3;];[4;5;6]]]
Benjol 2010年

h!伙计-我真的在寻找一种可以自己动手做的方法。
凯文(Kevin)

List.concat绝对是这样做的方法,在我发现它正在使用之前List.collect id
Dave Glassborow

0

浮点数的列表理解

[23.0 .. 1.0 .. 40.0]被标记为不赞成使用的几个版本。

但显然,这可行:

let dl = 9.5 / 11.
let min = 21.5 + dl
let max = 40.5 - dl

let a = [ for z in min .. dl .. max -> z ]
let b = a.Length

(顺便说一句,那里有一个浮点陷阱。在fssnip发现-F#代码段的另一个地方)


这是不是稳定的,看到stackoverflow.com/questions/377078/...
Goswin

-2

平行地图

let pmap f s =
    seq { for a in s -> async { return f s } }
    |> Async.Parallel
    |> Async.Run

7
异步工作流会导致CPU密集型工作的高开销和较差的负载平衡,因此这对于并行性而言是一个不好的解决方案。Array.Parallel.map现在最好使用内置的。
JD 2010年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.