F# Merge/join seq of seqs

Slowly getting the hang of List matching and tail recursion, I needed a function which 'stitches' a list of lists together leaving off intermediate values (easier to show than explain): merge [[1;2;3];[3;4;5];[5;6;7]] //-> [1;2;3;4;5;6;7] The code for the List.merge function looks like this: ///Like concat, but removes first value of each inner list except the first one let merge lst = let rec loop acc lst = match lst with | [] -> acc | h::t ->

F# What makes FSharpFunc<> faster than Func<>?

I'm curious about the performance enhancements that have been made for FSharpFunc<>. Is it the fact that it does not contain multiple delegate so there is no need to loop over all the references when firing a function call ? Anything else ?

F# Am I missing something, or do we have a couple inconsistencies / misnomers?

Mathematicians typically count starting with 1, and call the counting variable n (i.e. "the nth term of the sequence). Computer scientists typically count starting with 0, and call the counting variable i (i.e. "the ith index of the array"). Which is why I was confused to learn that Seq.nth actually returns the "n+1 term of the sequence". Doubly confusing is that Seq.iteri does as it's name implies and traverses a sequence supplying the current index. Am I missing something? Is there a rationa

F# Javascript quotations

is anyone working in F# with quotations for javascript? I am thinking of a project and would like some input.

F# Dynamic cast to Interface

According to the post http://cs.hubfs.net/forums/thread/3616.aspx, I need to use a function like the following to cast an object to an interface, I have run a test, this is still true, the bug of :?> is still not fixed. let cast<'a> o = (box o) :?> 'a let ci = { new Customer(18, Name = "fred") with override x.ToString() = x.Name interface ITalk with member x.Talk() = printfn "talk1111111" } let italk = cast<ITalk>

F#: Class with no default constructor as type parameter?

I have a FileReader class whose job is to read and process text files using a StreamReader. To facilitate unit testing, I'd like to provide a type parameter to this class so that I can swap the StreamReader for a FakeReader that doesn't actually interact with the file system (and maybe throws exceptions such as OutOfMemory, so I can test the error handling in FileReader). Ideally, I'd like to define FileReader something like this (trivialized for clarity): type FileReader<'Reader> =

F# write records just in time when the value (for id of something) is changing

How to write records just in time when the value for id of something is changing ? id for each record when ture->false and false->true for some list? for example table id value 1 0 2 0 2 0 2 0 1 0 2 1 --> the only changes here 2 1 1 0 2 0 --> and here (node with id 2 changed 1 -> 0 ) 1 1 --> node with id 1 changed 0 -> 1 result table 2 1 2 0 1 1 my idea is not functional and a bit weird, I'm thinking about functional or linq way of making the same.

Why is the member dictionary in this f# code always empty?

I want to scrape a page for all the urls and put them in the dictionary. I created an class with an dictionary. But I can't seem to add elements into it. type crawler = new()= {} member this.urls = new Dictionary<string,string>() member this.start (url : string)= let hw = new HtmlWeb() let doc = hw.Load(url) let docNode = doc.DocumentNode let links = docNode.SelectNodes(".//a") for aLink in links do let href = aLink.Get

Scaling a sequence in F#

I am trying to scale a sequence by the first element of the sequence, so the first element will always be one, and then subsequent elements are a ratio of the first element to the nth element of the original sequence. Here is my code, open System open System.Collections let squish1 (x:Double seq) = let r = (Seq.head x:Double) Seq.fold (fun (xi:Double) (r:Double) -> xi/r);; And I test on this little vector:- squis

F# Are there FP names for operator that pipes an operation into innermost structure ? (similar to the |> operator in fsharp)

I had to write 2 operators : let inline (|/>) (seqinit:seq<'a*'T>) f = seqinit |> Seq.map (fun (key1 ,seq1) -> (key1, seq1 |> f )) let inline (||>) (seqinit:seq<'a * seq<'b>>) (f2:seq<'b>->seq<'c*seq<'d>>) = seqinit |> Seq.map (fun (key1 ,seq1) -> (key1, seq1 |> f2 )) In order to have the following operations, the first group transforming Seq's to Map's, the second group adding a key to a collection let toMap (seqinit:seq<

F# Is it possible to open a namespace provided by a Type Provider?

Is there any way to open a namespace of types provided by a type provider implementation? I ask, because some of the generated type name paths are very long and ugly in code. I have used type abbreviations to alleviate this, but obviously this is a manual process. The F# open keyword does not support this. Is there another way? Update: as pointed out in the answer and comments this is wrong. You can open a type provided namespace. I had not realised I was looking at deeply nested types, no

F# and explicit conversion in LINQ to XML

In C# I can express this: var xe = XElement.Parse("<foo></foo>"); var maybe = (bool?)xe.Element("bar"); How can this be expressed in F#? Edit: I did find this helper function let inline conv (x : ^a) : ^b = ((^a or ^b) : (static member op_Explicit : ^a -> ^b) (x))

F# Can I extend built-in array's indexer?

I want to add my own indexer to generic array type: type 'T``[]`` with member this.Item(x: string) = 1 // test However, this gives a compile error "expression was expected to have type int but here has type string (FS0001)." let a = [|1|] let b = a.["aa"] // error: FS0001 let c = a.Item("aa") // this works. I found this question which was asked 3 years ago and the answer suggested it's an FSharp bug. Want to confirm if it is still the case, or whether the specification has been

Making a try-with block smaller in F#?

So I have this sample piece of code, and I want to add a try-with block inside it: static member private SomeFunc (someParam: list<DateTime*int>) = let someLocalVar = helpers.someOtherFunc someParam let theImportantLocalVar = List.fold helpers.someFoldFunc ([],someLocalVar.First()) someLocalVar.Tail let first = fst theImportantLocalVar let tail = someParam.Tail helpers.someLastFunc(first,tail,theImportantLocalVar)

F# FsUnit `should equal` fails on `Some []`

When I run this FsUnit test with NUnit 2.6.3, let f xs = Some (List.map ((+) 2) xs) [<Test>] let test() = f [] |> should equal (Some []) I get: Result Message: Expected: <Some([])> But was: <Some([])> Result StackTrace: at FsUnit.TopLevelOperators.should[a,a](FSharpFunc`2 f, a x, Object y) The test fails even though the Expected and Actual in the message are the same. What happened?

F# Compiler can't tell which record type with duplicate fields should be the function parameter type

My program has a few record types with the same field names (each record type means something different). The compiler insists function parameters matching this record shape must be of the last type declared, even though I'm declaring record instances with unambiguous field names, and always passing a consistent type into each function. What is the appropriate way to deal with this? I know I could put a type annotation on the functions, but I feel like if I'm doing things the Right Way, I shoul

Changing F# application icon

I'm developing Windows Application using Visual Studio 2013 and F# but I can't change default application icon. I have tried to create a C#-WPF application for font-end, it work. But I don't want to use C# for font-end. I also tried resource hacker after building my application, but it is just not working.

F# Read list of int from Console

Here is what I want: let rec getList (cnt:int, acc: int list): int list = if cnt = 0 then acc else let n = Console.ReadLine() |> int getList (cnt-1) n::acc And call it like this: getList 10 [] To read 10 integers from standard input and return list of 10 integers. But I get the error: getList (cnt-1) n::acc --------^^^^^^^^^^^^^^^ /Users/demas/temporary/stdin(890,9): error FS0003: This value is not a function and cannot be applied Why ?

F# Is there a List Module Function that is like unzip with a Transformer

Is the below something I would find in the standard library? split transformer1 ([], []) [("Foo", 1); ("Bar", 2); ("FooBar", 3)];; > val it : string list * int list = (["FooBar"; "Bar"; "Foo"], [3; 2; 1]) here is my implementation let split transformer defval stream = let rec split' s acc = match s with | [] -> acc | x::xs -> split' xs (transformer x acc) split' stream defval let transformer1 (key, item) (akey, aitem) = (key::akey, item::aite

F# pattern matching on records with optional fields

F#'s 'options' seem a nice way of using the type system to separate data that's known to be present from data which may or may not be present, and I like the way that the match expression enforces that all cases are considered: match str with | Some s -> functionTakingString(s) | None -> "abc" // The compiler would helpfully complain if this line wasn't present It's very useful that s (opposed to str) is a string rather than a string option. However, when working with records t

How to simplify this F# code

Isn't there a cleaner way to do this? let Triplets = List.zip3 A B C let T1 (x, _, _) = x let T2 (_, x, _) = x let T3 (_, _, x) = x let Best = List.maxBy T3 Triplets T1 Best,T2 Best // return to C# code

How do I iterate over a hashtable in F#?

fails to compile. I've tried using Array.filter, Seq.filter, List.filter I've tried getting just the dic.Keys to iterate over but F# doesn't seem to want me to coerce a KeyCollection into an IEnumerable. I've tried upcasting the hashtable into an IEnumerable<KeyValuePair<string,string>> How do I walk the hashtable that is returned from Environment.GetEnvironmentVariables() ?

F# Is there a less clumsy way to perform automatic numbering with infinite sequences?

While the code I have does what I need, I feel I am missing some coding technique to implement this kind of stuff in a more concise way. The goal is to compose items and give them an Id value along the way. Here the code which I feel can be simplified and improved in many ways. If only I knew, how... type Foo = | A of int | B of int | C of int let ids startvalue = Seq.initInfinite (fun i -> i + startvalue) let makeA ids = A(Seq.head ids), Seq.skip 1 ids let makeB ids = B(Seq.head id

creating stock returns from prices in f#

I have log stock prices as an array in F# let stockprice= Array.zip D12 index |> Array.map (fun (a,b) -> a+b) |> Array.map(fun x -> log(x)) However, I cannot figure out how to turn the stock prices to returns, by dividing Pt by Pt-1. Following code does not work: let myreturn= stockprice.diff(1) Does anyone have any suggestions?

F# Literal/constant can be composed with strings, but not int?

Why is this OK: let [<Literal>] hi = "hi" let [<Literal>] bye = "bye" let [<Literal>] shortMeeting = hi + bye ...but this is not? let [<Literal>] me = 1 let [<Literal>] you = 1 let [<Literal>] we = me + you The third line gives the error: This is not a valid constant expression What's up with that?

Modeling constrained tree data structures in F#

As a beginning F# programmer, I've read articles like this one that describe how to model simple tree data structures in F#. I'd like to model more complex tree data structures. Consider a tree that consists of a single root that has a number of child nodes (primary nodes), each of which has a number of nodes (secondary nodes). Let's say there are three flavors of trees, which are based on the kind of root (notice I say "kind" rather than "type" - I'm not trying to assume any model yet.) Roo

In F#, how do I initialize static fields in a type with no primary constructor?

I have an F# class that derives from a .net class with multiple constructors. To expose them all, I implement a type with no primary constructor. Now I would like to add a static field. How do I initialize the static field? Consider this: type MyType = inherit DotNetType [<DefaultValue>] static val mutable private myStatic : int new () = { inherit DotNetType() } new (someArg:string) = { inherit DotNetType(someArg) } Now, how do I initialize the "myStatic" field in a way

F# CsvProvider skips first row with data

There is a CSV file without headers. Only the rows with data. In order to set the headers I use sample. type DisaggreggatedFinancialData = CsvProvider<"Schema.csv", HasHeaders=true, AssumeMissingValues=true, MissingValues="."> When loading a file CsvProvider is not reads the first row of data. Data is only available from the second row. When specify the parameter HasHeaders = false, then the sample headers are not available. How to set headers and read data from the first row?

How do I await an async method in F#

How do I await an async method in F#? I have the following code: type LegoExample() = let brick = Brick(BluetoothCommunication("COM3")) let! result = brick.ConnectAsync(); Error: Unexpected binder keyword in member definition Note, I reviewed the following link: However, I only observe the functional technique and not the OOP technique.

F# How do I pass an argument into Async.RunSynchronously?

How do I pass an argument into Async.RunSynchronously? I am attempting to do the following: Async.RunSynchronously (moveAsync brick) Of course, this does not compile: The value or constructor 'brick' is not defined I updated my code but am still running into the same issue regarding passing in an argument into Async.RunSynchronously Client: open LegoCommands [<EntryPoint>] let main argv = connectAsync |> Async.RunSynchronously |> ignore moveAsync |> Async.R

F# What causes a breakpoint to fail to bind?

What causes a breakpoint to fail to bind? I receive an error when attempting to execute the following expression: let grid_1 = { grid with Four= grid |> update };; // Updated here The error I receive is as follows: Code: type State = Alive | Dead type Response = | Survives | Dies | Resurected type Grid = { Zero:State One:State Two:State Three:State Four:State // Central Five:State

Combination monads in F#

I'm trying to get my head around monads in F#, and am looking for an example of composing them. In haskell it looks like you would use Monad Transformers but in F# it appears that you would create your own computation expression builder. I can get behind that, but are there any examples of some combinations of the standard monads and how to use them? I'm particularly interested in combining Reader, Writer and Either to build functions that take in an environment, tweak it, and then using Writ

F# Assignment to mutable variable interferes with type inference of otherwise valid calculation

I'm attempting some Newton Raphson updates. Here is a piece of code that compiles and runs (warning: infinite loop). let thetam = [|beta; sigSq|] |> DenseVector let mutable gm = grad yt xt betah sigSqh // returns DenseVector let hm = hess yt xt betah sigSqh // return Matrix<float> while gm*gm > 0.0001 do gm <- grad yt xt betah sigSqh thetam - (hess yt xt betah sigSqh).Inverse() * gm // unassigned compiles However, as soon as I assign the last value to the mutable v

F# Failure running WebSharper 4.0 tutorial

I am learning how to use WebSharper. Actually, I am failing to learn how to use WebSharper. I wanted to learn how to build a simple SPA so I followed this tutorial from the WebSharper page. I am able to create the SPA with Visual Studio and Zafir (the codename for WebSharper 4.0 that is in beta). I followed every step in the tutorial. I have created a repo on github that is everything in the SPA. The project won't build. More specifically, in the Client.fs file, I get compiler error Th

F# tryHead is not defined

I am using Seq.tryHead but I am getting an error let maybeTagDatabaseModel = Seq.tryHead tagSeq error error FS39: The value, constructor, namespace or type 'tryHead' is not defined Does anyone have suggestions on how to fix? Thanks

F# What do I do with downloaded FsLab template?

Sorry for the question, but I am definitely not an "advanced" user. I installed the FsLab and FsLab Journal using NuGet. The instructions in https://fslab.org/download/ tell one to Download FsLab Journal template (which I did, and got a folder called FsLab.Templates-journal on my desktop). Next there is a link saying Install Visual Studio template. If I click on that I go to a page in the Visual Studio Marketplace with the title FsLab Journal and a green Download button. When I click on that

F# initializing private variable for subsequent usage

Can you initialize a private value in a module, and then later call another function to read the value? I'm getting an empty string though. data/Credentials.fs type Credentials = { mutable clientId: string; } Authentication.fs module Authentication = let private credentials = { clientId = "old"; } let init (claims: Credentials) = credentials.clientId <- claims.clientId // updating value let requestToken = printfn "reading %s\n" credent

F# FSharp.Data: CssSelect doesn't work as expected

Here a part of my HTML (if need - you can explore it completely here) I've checked this examples before but when I'm trying to parse article elements by doc.CssSelect "article[itemtype='http://schema.org/Product']" or doc.CssSelect "div.items.catalog-items > article" or doc.CssSelect "div.list.catalog-list article" all these give me no results, can't figure out why. Also, even this construction gives me nothing doc.CssSelect "div.list.catalog-list" But this

Creating a random fractional number in F#

I was trying to create a random fractional number as follows: type Fraction= { num: int den: int } let makeRandomFraction i = let n= fun i -> System.Random(i).Next(-50, 51) let d= fun i -> System.Random(i*3).Next(-50, 51) {num=n; den=d} but I am getting an error: error FS0001: This expression was expected to have type 'int' but here has type 'int -> int' Could you please explain the error and the correct way of doing the required.

F# generalization by overloading

Given the type type T = static member OverloadedMethod(p:int) = () static member OverloadedMethod(p:string) = () Let's suppose we want to create a generic function that resolves to the specific overload based on the type of the parameter. The most intuitive way would be //Case 1 let inline call o = T.OverloadedMethod o //error call 3 call "3" but this, despite the inline definition, doesn't work and the compiler complains Error FS0041 A unique overload for method 'Overloade

How to make an Abstract class that inherits an interface in F#?

I have the following code with an interface and an abstract class. type INode<'a> = abstract member Parent:INode<'a> abstract member Evaluate:unit->'a abstract member Clone:INode<'a> -> INode<'a> abstract member SelectRandom:int->INode<'a> option [<AbstractClass>] type TerminalNode<'a>() = interface INode<'a> with member this.SelectRandom indexOfCurrentNode = let p = 1.0 / float indexOfCurrentN

Ignoring backslash and double quotes in F#

How do we ignore backslashes in a string? I tried this but it dosen't work: let str2 = @"I igonore \ \ \ / / / / backsalshes" printfn "%s" str2 Also, I thought ignoring double quotes in a string is as follow: let str3 = """ "I ig""onore double quotes and backslasehes " """ printfn "%s" str3 Again, It printed a string with the double quote 'ig""onore'. What is wrong?

Passing a list from C# to F#, how to specify the parameter is a list?

With the following C# code var MyList = new List<MyClass>(); SomeFSharpFunc(MyList); on the F# side: let SomeFSharpFunc (MyList: ???What do I put here so I know it's a list) = I don't know to how express that the incoming parameter is a list. Also, do I need to duplicate the C# class as a F# type?

F# How to build integrations tests for a Saturn app

I'm trying to build some integration tests for a small API I've built using the Saturn framework. The API is built with the usual Saturn computation expressions such as application, controller, router etc. But in order to build integration tests I need to replace the application computation expression (ce) and hand craft a WebHostBuilder. My application ce looks like this: module Server let app = application { url ("" + port.ToString() + "/") use_rou

What nullable type to use for varbinary column in F# EFCore?

I have an MSSQL database column that is a nullable varbinary(8). When I try to make the field nullable in my F# record, i get the following error: "A generic construct requires that the type 'byte[]' have a public default constructor" Neither Nullable<byte[]>, Nullable<Byte[]>, Nullable<Byte list> or Nullable<seq<byte>> get beyond this error. I have omitted other fields for brevity. [<Table("SurveyResponse"); CLIMutable>] type SurveyResponse = {

Controlling access on fields in F# types

I'm writing Domain Logic for one of the application using F#. I want to control access on fields defined for a type in F# so that I can implement builder pattern and control type instantiation. Want to do something similar with do in builder pattern in C#/Java. Kindly suggest. e.g. let Person = { Name:string Age:number Salary:string } So I want to make sure person should always be instantiated with Name and Age. But salary should be optional. Instantiation should happen in a buil

how can I build a format string with sprintf, in F#?

I'm trying to go from: sprintf "%3.1f" myNumber to: sprintf myFormatter myNumber which is not possible I have a situation where number precision depends on some settings, so I would like to be able to create my own formatter string. I know it can be done with String.Format, but I am curious if there is a F# way with sprintf, or ksprinf; can it be done?

final output of Result, in F#

This seems like a question that has an ultra simple answer, but I can't think of it: Is there a built in method, within Result, for: let (a: Result<'a, 'a>) = ... match a with | Ok x -> x | Error e -> e

  1    2   3   4   5   6  ... 下一页 最后一页 共 36 页