然而,我在这里寻找的是有用的片段,可重复使用的小'帮助'功能。或者模糊但又漂亮的模式,你永远不会记得。
类似的东西:
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/。
答案 0 :(得分: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"
答案 1 :(得分:27)
Perl样式正则表达式匹配
let (=~) input pattern =
System.Text.RegularExpressions.Regex.IsMatch(input, pattern)
它允许您使用let test = "monkey" =~ "monk.+"
表示法匹配文本。
答案 2 :(得分: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#编译器看到一个反斜杠后跟一个字符串文字中的回车符时,它会删除从反斜杠到下一行的第一个非空格字符的所有内容。这允许您使用排成行的多行字符串文字,而不使用一串字符串连接。
答案 3 :(得分:24)
通用备忘录,由the man本人提供
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
答案 4 :(得分: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
答案 5 :(得分:17)
对于需要检查空的
的性能密集型内容let inline isNull o = System.Object.ReferenceEquals(o, null)
if isNull o then ... else ...
比
快20倍if o = null then ... else ...
答案 6 :(得分:11)
活动模式,又名“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
答案 7 :(得分: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
答案 8 :(得分:8)
也许monad
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()
以下是对于未经证实的人monads的简要介绍。
答案 9 :(得分: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()
答案 10 :(得分: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>
答案 11 :(得分:6)
转置列表(见Jomo Fisher's blog)
///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
如果我很聪明,我会尝试将其与异步并行...
答案 12 :(得分:6)
(我知道,我知道,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(参见this question)。
我目前看不到使用此方法直接转换字典的方法,而不是
(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; } ...
答案 13 :(得分: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]
答案 14 :(得分: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)
答案 15 :(得分:4)
数组的加权和
基于权重的[k-数组]计算[数组的k-数组]的加权[n-数组]和
(从this question和kvb的answer复制)
鉴于这些数组
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),该函数(对于每个权重)应用于每个数组编曲。
第二行:Array.reduce类似于fold,除了它从第二个值开始并使用第一个作为初始“状态”。在这种情况下,每个值都是我们的数组数组的“行”。因此在前两行上应用Array.map2(+)意味着我们对前两个数组求和,这为我们留下了一个新数组,然后我们将(Array.reduce)再次加到下一个数组上(在本例中为last)阵列。
结果:
[|0.060123; 0.069444; 0.07296; 1.5510666; 215.40356|]
答案 16 :(得分:4)
效果测试
(找到here并更新了最新版本的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))
答案 17 :(得分:3)
F#,DataReaders的DataSetExtensions
System.Data.DataSetExtensions.dll添加了将DataTable
视为IEnumerable<DataRow>
的功能,以及通过支持系统优雅地处理DBNull
的方式取消装箱单个单元格的值。可空。例如,在C#中,我们可以获得包含空值的整数列的值,并使用非常简洁的语法指定DBNull
应该默认为零:
var total = myDataTable.AsEnumerable()
.Select(row => row.Field<int?>("MyColumn") ?? 0)
.Sum();
然而,缺少DataSetExtensions有两个方面。首先,它不支持IDataReader
,其次,它不支持F#option
类型。以下代码同时执行 - 它允许将IDataReader
视为seq<IDataRecord>
,并且可以从读者或数据集中取消装箱值,并支持F#选项或System.Nullable。结合选项合并运算符in another 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)
答案 18 :(得分:3)
好的,这与片段无关,但我一直忘记这一点:
如果您在交互式窗口中,则按 F7 跳回代码窗口(不取消选择刚刚运行的代码...)
从代码窗口转到F#窗口(以及打开F#窗口)是 Ctrl Alt F
(除非CodeRush窃取了你的绑定......)
答案 19 :(得分:2)
成对和成对
我总是期望Seq.pairwise给我[(1,2);(3; 4)]而不是[(1,2);(2,3);(3,4)]。鉴于List中既不存在,又需要两者,这里是未来参考的代码。我think they're tail recursive。
//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 []
答案 20 :(得分:2)
创建XElements
没有什么了不起的,但我一直被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"
答案 21 :(得分: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启发的这项技术有一种模糊的记忆,但现在找不到参考资料)
答案 22 :(得分: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))
答案 23 :(得分:1)
Pascal的三角形(嘿,有人可能觉得有用)
所以我们想要创建这样的东西:
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] = 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]
答案 24 :(得分: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
答案 25 :(得分: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.
答案 26 :(得分: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窗体对话框输入/输出来找出如何消除这些函数的文件要求。要显示的代码太多,但对于那些想做这样的事情的人来说,就是我解决它的方式。
答案 27 :(得分: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
答案 28 :(得分: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#片段的另一个地方)
答案 29 :(得分:-2)
平行地图
let pmap f s =
seq { for a in s -> async { return f s } }
|> Async.Parallel
|> Async.Run
答案 30 :(得分:-2)
将记录设为null
type Foo = { x : int }
let inline retype (x:'a) : 'b = (# "" x : 'b #)
let f : Foo = retype null