w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
  Home » F# » Page 1
How to prevent eager evaluation?
The problem is that you are not defining functions, but values. When you write the following in F#: let test = printfn "Hi" ... you are defining a value test that has a type unit (similar to void in C#) which is evaluated immediately and the result of the expression is stored in a value named test. The result of the expression is a unit value (which you cannot do much with), but it is a val

Categories : F#

Using Task.FromResult(0) from FSharp
It looks like DeliverAsync returns a Task, so you need both branches to return a Task. Task.FromResult(0) returns a Task<int> so you need to explictly upcast it to a Task: else Task.FromResult(0) :> Task

Categories : F#

F#: Creating a collection of integers from user input
In the match branch | true -> getNumList num::listSoFar You should use parenthesis: | true -> getNumList (num::listSoFar) Because function application has higher priority than the :: operator

Categories : F#

Using type from F# host via Ajax in FunScript JS code
Could you please post some code to see better what you're exactly trying to do? For reference, you can see an example of how to exchange type-safe JSON values using FunScript.HTML extensions in this little project. In this case: Types are shared between server, client and database using F# records with CLIMutable and System.Data.Linq.Mapping.Table attributes: Source For the server, I'm using ASP

Categories : F#

F# optional arguments and overloading alternatives
I think option 1 (with curried function) would be simplest. Curried functions are pretty common in functional programming. In options 2 or 3 you'll still have to pass additional parameter to the function for the search from the beginning Options 4 or 5 require additional overhead to create type. It's kind of 'overkill' for this simple task

Categories : F#

FsCheck test change the range of values used for testing
By default, FsCheck generates integers between 1 and 100. You can change this by supplying a Config object to the Check. let config = { Config.Quick with EndSize = 4999 } Check.One(config,test) EndSize indicates the size to use for the last test, when all the tests are passing. The size increases linearly between StartSize, which you can also set should you wish to generate test data in

Categories : F#

F# How to have a value's type determined by a match statement?
In F#, there are no statements, only expressions, and each expression has to have a single concrete type. A match block is an expression as well, meaning that it has to have a single concrete type. What follows from that is that each case of the match has to have the same type as well. That is, something like this is not valid F#: let foo = // int? string? match bar with /

Categories : F#

FAKE Fsc task is writing build products to wrong directory
This, or a very similar problem, was reported in FAKE issue #521 and seems to have been fixed in FAKE pull request #601, which see. Explanation of the Problem As is apparently well-known to everyone but me, the F# compiler as implemented in FSharp.Compiler.Service has a practice of skipping its first argument. See FSharp.Compiler.Service/tests/service/FscTests.fs around line 127, where we see

Categories : F#

F# Avoid active pattern overwriting
I think your concerns apply to shadowing in general and not just active patterns. How often will you define two active patterns whose parameters and return values are the same and have overlapping case names? Generally, types mitigate potential shadowing problems. Along these lines, type annotations are your friend.

Categories : F#

F# - Weird FileNotFound Exception
Make sure to run the program as an administrator - new StreamReader(string) does not mention a specific exception when file permissions are violated, and thus may be wrapping it. Note that File.Open and the aformentioned File.ReadAllText methods mention specific exceptions when encountering access violations, and thus may throw more descriptive (helpful) exceptions.

Categories : F#

Using decimal values in FunScript
It is rather JavaScript limitation because JavaScript has only binary floating point. One of the solution would be creating your own type containing two integers: for integer part and fractional part

Categories : F#

Type inference with List.fold
In your second example, you haven't specified the initial value for the fold. You probably meant something like |> List.map (List.fold (fun acc elem -> acc * elem) 1)

Categories : F#

Can I Access Parameters of a Computation Expression?
let bindings in class definitions are always private. You can define a member instead. For an easy solution, you could do: let formlet = FormletBuilder(ctx) let person = formlet { let! id = formlet.get_int "id" ... }

Categories : F#

F#, FParsec, and Updating UserState
So basically, what you want to do in pHeader is to use the parser as a monad, rather than an applicative. Based on your code style you come from Haskell so I'll assume you know these words. Something like this then: let pHeader = let includesBoundary s = undefined let setBoundary b = { Boundary=b } in delimited3 ":" ";" "=" blankField |>> makeHeader

Categories : F#

Get the `Middle` of a string with certain prefix and postfix?
I think it's fine. Why do you think it's not functional? I would change only the last line in order to use string slices: if input.StartsWith(prefix) && input.EndsWith(postfix) && input.Length > prefix.Length + postfix.Length then Some(input.[prefix.Length .. input.Length - postfix.Length - 1]) else None Anyway I don't think it makes it more functional.

Categories : F#

constraining type in Seq.scan
As precised in the comment, I was opening the namespace of some other library further up in my file. Being a C# library, it redefines its own Set (poor folks) Doing so, writing Set<_> induced the compiler in picking up their version, whilst Set.add still refered to the trusted FSharp Set<_>. Eventually, the two came in brutal head to head conflict with each other.

Categories : F#

getting the MonoBrickFirmware.dll library ev3 Button value as hexadecimal in F#
The button events work in the following way in F# (you can just copy the code into Program.fs file in a newly created F# Console application): module MyEV3FSharpExperiment open MonoBrickFirmware.UserInput open MonoBrickFirmware.Display open System.Threading // The main function that is called when the EXE is run on MonoBrick. [<EntryPoint>] let main argv = let terminateProgram = new

Categories : F#

Extending Database Objects / Downcasting from Base
F# does this kind of thing with type extensions: type DbContext.ServiceTypes.Address with member this.Add() = use db = DbContext.GetDataContext() db.Address.InsertOnSubmit this db.DataContext.SubmitChanges() member this.Remove() = use db = DbContext.GetDataContext() db.Address.DeleteOnSubmit this db.DataContext.SubmitChanges() membe

Categories : F#

F#, FParsec, and Calling a Stream Parser Recursively
This is a fragment that might get you going in the right direction. Get your parsers to spit out something with the same base type. I prefer to use F#'s discriminated unions for this purpose. If you really do need to push values into a Post type, then walk the returned AST tree. That's just the way I'd approach it. #if INTERACTIVE #r"""....FParsecCS.dll""" // ... edit path as appropriate

Categories : F#

F# tail call optimization issues on Mono
I tested a Fibonacci implementation passing an accumulator instead of a function (continuation) like this: let fib n = let rec _fib i (a,b) = match i with | 0 -> a | _ -> _fib (i-1) (b, a+b) _fib n (0,1) which worked fine on Mono, i.e. no stack overflow. So I guess it's only an issue with TCO when using continuations. There's a Xamarin ticket from June 2013 addre

Categories : F#

Changing F# application icon
I assume you are trying to set the icon of a command-line application. This isn't possible. Only desktop applications have icons. Console applications have no window, hence no icon. You can specify an icon when you create a shortcut to the application (eg during setup) but that has nothing to do with the application itself. Visual Studio 2013 contains only an F# console application. If you want t

Categories : F#

Unexpected keyword 'val' in definition
The val keyword in F# (unlike 'val' in ML) is used to declare a field in a class or structure type without initializing it. http://msdn.microsoft.com/en-us/library/dd469494.aspx if you want to define mutable value in the Module you can use let mutable... By the way, if you define the value with the same name (like 'nums') twice or more times then the effective value for the compiler will be

Categories : F#

Pattern match guard with DateTime.TryParseExact?
You can use a mutable: let mutable dt = Unchecked.defaultof<_> match argList with | "ccc" :: yyyymm :: [] when DateTime.TryParseExact(yyyymm, "yyyyMM", CultureInfo.InvariantCulture, DateTimeStyles.None, &dt) -> ... But an active pattern makes the match much clearer:

Categories : F#

Why fsharp autogenerated gethashcode generates too many collisions?
I am no expert on the overall algorithm used to produce auto-generated Equals and GetHashCode, but it just seems to produce something non-optimal here. I don't know offhand if that is normal for a general-purpose auto-generated implementation, or if there are practical ways of auto-generating close-to-optimal implementations reliably. It's worth noting that if you just use the standard tuple, th

Categories : F#

Action and 'T -> 'U -> unit conversion
The argument list of a delegate is not a tuple. If F# were to allow new Action<_,_>(fun (_, _) -> ()) (invalid code), this would be no less arbitrary. If this were allowed, an F# function taking a tuple to unit would be converted to a CLI delegate with two parameters and void return type. In actual F#, as you said, the valid form is to provide a function with two curried parameters and un

Categories : F#

Why upcast is not necessary in this let bound function?
Have a look at the F# spec where it says: This means that F# functions whose inferred type includes an unsealed type in argument position may be passed subtypes when called, without the need for explicit upcasts. For example: (The example showed there is almost the same as yours) Also note that for let bound functions upcasting is automatically except in some cases, for example when the argumen

Categories : F#

F# struct declaration with private constructor
I think that definition using [<Struct>] and primary constructor is generally preferred (at least, it looks nicer to me!) but I believe the following definition using struct .. end is equivalent to what you're doing: type AngularSpeed = struct val mutable angle : float val mutable speed : float val mutable time : float private new (angle: float, speed: float, time: float) = { an

Categories : F#

Websharper / Web.Control constructor issue
What happens is that values passed to the constructor of a Web.Control are server-side values that get serialized to JSON during the server-side construction of the page. However, there is no serializer for the type obj, so the serialization of your inputDataTable (of type obj[][]) fails. In contrast, in the version that works, inputDataTable is constructed on the client, so no serialization needs

Categories : F#

Disjunctive Normal Form Formula
I'm not sure I understand the question, but here is what I came up with: let litOf = Set.ofSeq let dnfToSet a = let isNotSuperset bci = a |> Set.forall(fun bcj -> (bci = bcj) || not(Set.isSuperset bci bcj)) a |> Set.filter isNotSuperset The following illustrates: type bc = A | B | C | D let bc1 = litOf [A; B; C] let bc2 = litOf [B; C; B] let bc3 = litOf [C; B; A] let bc4 = li

Categories : F#

MissingManifestResourceException for FSharp.Core assembly
This might be a bug in the VS F# portable profile support. Possibly a compiler bug (somehow this version of FSharp.Core is not properly fitted onto the portable profile), or possibly a project system bug (some kind of required build output is not getting created properly for ARM). I would recommend opening this as a bug at https://visualfsharp.codeplex.com/

Categories : F#

Modelling dice rolls in F#
As one of the options you could create your own numeric type as described in this post by Tomas Petricek: http://tomasp.net/blog/fsharp-custom-numeric.aspx/index.html

Categories : F#

FSharp Compound List
There are many ways but I think this is a clean one: [1;2;3;4;5] |> List.scan (fun x y -> x @ [y]) [] |> List.tail using List.scan and finally List.tail to omit the first element which is an empty list.

Categories : F#

The most appropriate way to return a hot, awaited task from F# to a caller in C# framework
Using Async.AwaitTask and Async.StartAsTask is the way to go. Although you do not really need to return anything from the async if you just want to return a non-generic Task: member x.DoAsync(x:int) = let work = async { if x = 10 then do! taskContext.ReturnAsync() |> Async.Ignore } Async.StartAsTask(work) :> Task

Categories : F#

Unexpected identifier and indentation problems
It's the lines following environment that are the problem - the let binding is already finished, but they're indented for no reason. You want to have this (in an fsx you can drop the do, but you need to unindent those lines): let environment = new System.Collections.Generic.Dictionary<string, value>() do environment.["x"] <- 2I environment.["y"] <- 3I let lookup name =

Categories : F#

FAKE specify NUnit Namespace/Fixture when running tests
Newest version of FAKE added support for Fixture parameter. You should be able to do: Target "Tests" (fun _ -> testDlls |> NUnit (fun p -> {p with Fixture ="Namespace.Unit" DisableShadowCopy = true; OutputFile = artifactDir + "/Unit-TestResults.xml" }) testDlls |> NUnit (fun p -> {p with Fixtu

Categories : F#

does a tee function exist somewhere in F# library?
The closest I've seen is actually in WebSharper. The definition is: let inline ( |>! ) x sideEffect = do sideEffect x x Usage: (x |>! printf "%A") |> nextFunc

Categories : F#

Why are functions bound to the first type they are passed
You have to declare your method using inline keyword to make it work: let inline my_func (x,y) = x + y Read more on MSDN: Inline Functions (F#)

Categories : F#

unpivot a deedle dataframe
I don't think we have any built-in function to do this automatically in Deedle, but you can do that by iterating over the rows of the frame and then iterating over the columns: Assuming f is the sample input frame from your question, the following should do the trick: [ for r in f.Rows.Values do for c in r.Keys do if c <> "cola" then yield r.Get("cola"), c, r.TryGet(c) ]

Categories : F#

IntPtr and UIntPtr literals
Those are two separate things - the list contains all the literal strings that are supported, but not all of them can be marked with Literal attribute. I think the wording of the comment below the table is a bit unfortunate. BigInt and IntPtr are structs, and that might be why they can't be declared as consts (I believe this is what the attribute boils down to). It seems that this is the case in

Categories : F#




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.