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/创建了一个站点。

4

31 回答 31

28

Perl 风格的正则表达式匹配

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

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

于 2009-09-25T13:07:09.167 回答
28

中缀运算符

我从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"
于 2010-09-22T00:44:33.070 回答
27

多行字符串

这是非常微不足道的,但它似乎是 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# 编译器在字符串文字中看到反斜杠后跟回车时,它将删除从反斜杠到下一行第一个非空格字符的所有内容。这允许您拥有排列的多行字符串文字,而无需使用一堆字符串连接。

于 2010-09-24T16:40:00.727 回答
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
于 2009-05-12T06:40:30.533 回答
19

对文本文件的简单读写

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

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  
于 2009-05-07T08:58:58.050 回答
18

对于需要检查 null 的性能密集型内容

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

大约快 20 倍

if o = null then ... else ...
于 2010-10-13T21:29:29.260 回答
11

Active Patterns,又名“Banana Splits”,是一种非常方便的构造,可以让一个匹配多个正则表达式模式。这很像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
于 2009-05-08T16:03:55.970 回答
8

'Unitize' 一个不处理单元 的函数使用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致敬

于 2009-09-11T20:21:42.003 回答
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()

这是一个简单的单子介绍。

于 2009-09-25T13:14:26.050 回答
8

选项合并运算符

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

/// 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()
于 2010-09-15T18:21:33.623 回答
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>
于 2010-09-07T09:13:38.357 回答
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

如果我很聪明,我会尝试将它与异步并行化......

于 2009-05-07T09:10:24.933 回答
6

F# Map <-> 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,here,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; } ...
于 2010-03-17T06:36:27.877 回答
5

LINQ-to-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)
于 2010-09-15T18:10:42.073 回答
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]
于 2009-10-07T15:12:35.693 回答
4

Performance testing

(Found here and updated for latest release of 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))
于 2010-03-10T06:08:46.143 回答
4

数组的加权和

基于 [k-array] 权重计算 [k-array of n-arrays] 数字的加权 [n-array] 总和

(从this questionkvb答案复制)

鉴于这些数组

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|]
于 2010-02-25T06:28:59.523 回答
4

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

如果您在交互式窗口中,您点击F7跳回代码窗口(不取消选择您刚刚运行的代码......)

从代码窗口转到 F# 窗口(以及打开 F# 窗口)是Ctrl Alt F

(除非 CodeRush 偷了你的绑定......)

于 2009-09-17T06:50:19.480 回答
3

F#、DataReaders 的 DataSetExtensions

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

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

但是,有两个领域缺少 DataSetExtensions。一是不支持IDataReader,二是不支持F#option类型。以下代码两者兼而有之 - 它允许将IDataReadera 视为 a seq<IDataRecord>,并且它可以从读取器或数据集中拆箱值,并支持 F# 选项或 System.Nullable。结合另一个 answer 中的选项合并运算符,这允许在使用 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)
于 2010-09-15T18:46:40.457 回答
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

(我对受Robert Pickering启发的这项技术有一个模糊的记忆,但现在找不到参考资料)

于 2009-09-25T06:59:14.640 回答
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"
于 2010-01-27T07:00:45.057 回答
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 []
于 2010-02-16T07:03:09.673 回答
2

一个方便的缓存功能,可以保存max (key,reader(key))在字典中并使用 aSortedList来跟踪 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))
于 2009-05-10T13:35:57.287 回答
1

日期范围

fromDate和之间的简单但有用的日期列表toDate

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
于 2010-09-21T21:56:39.087 回答
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 窗体对话框输入/输出来消除对这些功能的文件要求。代码太多要显示,但是对于那些想做这样的事情的人,这就是我解决它的方法。

于 2010-09-24T01:20:39.240 回答
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.
于 2009-09-25T07:29:11.523 回答
1

帕斯卡三角(嘿,有人可能会觉得它有用)

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

       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函数返回一个新列表,其中每个 item[i] = item[i] + item[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]
于 2009-11-19T18:27:28.507 回答
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
于 2010-10-12T20:21:19.733 回答
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# 片段的另一个地方)

于 2011-03-25T08:05:59.690 回答
-2

将记录设置为空

type Foo = { x : int }
let inline retype (x:'a) : 'b = (# "" x : 'b #)
let f : Foo = retype null
于 2010-10-13T21:30:45.793 回答
-2

平行图

let pmap f s =
    seq { for a in s -> async { return f s } }
    |> Async.Parallel
    |> Async.Run
于 2009-09-25T13:08:25.593 回答