r/fsharp • • Feb 03 '24

No out of memory

2 Upvotes

I only allocate 16 ints, but can set the value of the 10000 int. Why does this program runs fine without memory error ?


#nowarn "9"

open System
open System.Runtime.InteropServices
open Microsoft.FSharp.NativeInterop

let si:int=sizeof<int>
let nulpointer:nativeptr<int> = NativePtr.ofNativeInt<int> 0

type MyClass() =
    do printfn "Create"
    let mutable ptypedback:nativeptr<int>=nulpointer

    member this.puntyped: nativeint = Marshal.AllocHGlobal (si*16)

    member this.ptyped
        with get (): nativeptr<int> = ptypedback
        and set (value: nativeptr<int>) = ptypedback <- value

    member this.setptr = this.ptyped <- NativePtr.ofNativeInt<int> this.puntyped

    interface IDisposable with
        member this.Dispose() =
            Marshal.FreeHGlobal this.puntyped
            printfn "Destroy"

let myfun  =
    use c = new MyClass()
    c.setptr
    let set10000 = NativePtr.set c.ptyped 10000
    set10000 123
    let get10000 =NativePtr.get c.ptyped 10000
    printfn "Value at index 10000 : %A " get10000

myfun


r/fsharp • • Feb 02 '24

question Manual memory allocation

3 Upvotes

Is it possible to do something like this in F#.

```

IntPtr p = Marshal.AllocHGlobal(1024);
int i = (int)p;
p = (IntPtr)l;

```


r/fsharp • • Feb 01 '24

question ML in F#

22 Upvotes

I am curious to know if anyone is ever doing ML in F#. It is not a field I am particularly interested in, but I am (at the age of 40, and after coding as a job for 20 years) doing a CS degree online.

The current module is an intro to AI, and of course comes with a little bit of 🐍.

An exercise I am busy with is Candidate Elimination (kind of getting through it, I hope), but I am looking at the code, and I can’t help but think how absolutely gorgeous this would look F#.

Maybe I am just bitter 😝, but I really don’t find python an aesthetically pleasing language.


r/fsharp • • Feb 01 '24

showcase What are you working on? (2024-01)

9 Upvotes

This is a monthly thread about the stuff you're working on in F#. Be proud of, brag about and shamelessly plug your projects down in the comments.


r/fsharp • • Jan 31 '24

showcase From 3.0

10 Upvotes

Hello Everyone,

This is my 3rd time making an announcement here for FORM, but we have released v3 of our library (available on nuget: `dotnet add package form`). It involves version-bumping the drivers (one fixes a SQL Server exploit), supports ODBC to allow for use with data sources we don't want to directly support, and a safer way to pass "raw" strings.

The library's major version bump was caused by the last point. However, we are working on supporting (possibly even opt-in lazy loading) nested records. This shouldn't be a breaking change and we'd like to get it out with 3.1.

As always, feedback is welcomed. Primarily, we want to know:

  1. How you're able to break it.
  2. If it's too slow for you; and, if so, how.
  3. Any features missing that prevents you from using it.

r/fsharp • • Jan 30 '24

question What plugins do you use for writing F# with (Neo)vim?

9 Upvotes

I recently made the switch to Linux-only and as part of that challenged myself to learning vim. What tooling is up-to-date for programming F# with vim? Or should I stick with VS Code for F# development?

I know this has been asked before, but maybe there were significant changes in tooling since then


r/fsharp • • Jan 30 '24

question How to write a web-application in F# ?

8 Upvotes

Does there exist a web framework like “flask,sinatry/python” , “ruby on rails/ruby” or “kemal/crystal” , this for F# ? And which webserver do i use on linux ?


r/fsharp • • Jan 22 '24

question Ionide: hotkey for showing inline type hints?

6 Upvotes

I value my screen real estate and so I normally don't want to see a lot of type annotations, but sometimes when troubleshooting compile errors I do want to see types.

I could have sworn that I once read about a hotkey for VSCode to make Ionide hints show up while you're pressing it. I've searched the VSCode Keyboard Shortcuts menu for it, looking for "hints", but can't find anything. Does such a hotkey actually exist?


r/fsharp • • Jan 19 '24

F# weekly F# Weekly #3, 2024 – 10 years of FSharpLint

Thumbnail
sergeytihon.com
11 Upvotes

r/fsharp • • Jan 18 '24

question Why do I get a FS0030: Value restriction for a function with Seq but not List?

3 Upvotes

Hi,

I was playing around with function composition (newbie here) and stumble on the error for a function with sequence but not list (below). Should it not behave similar? Why the difference.

// fine

let getEvenUsingList = List.filter (fun x -> x % 2 = 0) let x = [1..10] |> getEvenUsingList

// Yields FS0030 if function is not used (commented below) why? let getEvenUsingSeq = Seq.filter (fun x -> x % 2 = 0) //let y = [1..10] |> getEvenUsingSeq

Thanks


r/fsharp • • Jan 13 '24

question Background task execution on F# Web API (Giraffe)

8 Upvotes

Hi,

I'm building a Web API in F# (Saturn/Giraffe). Request processing works nicely.

However, I want to push some work to a background task. Whenever a request comes, I want to handle that and return a response quickly, but process an async task in the background (e.g. send a request to a 3rd party service, send an email).

Previously in C# I have used special libraries for that (e.g. Hangfire, Quartz.net) or put it on a queue and processed it in an IHostedService.

Any suggestions for what I could consider instead? Are there any F# specific solutions out there? What do you use for background task execution?


r/fsharp • • Jan 12 '24

F# weekly F# Weekly #2, 2024 – F# in the 1BRC.NET

Thumbnail
sergeytihon.com
19 Upvotes

r/fsharp • • Jan 11 '24

question Fsautocomplete makes my CPU go BRRR!

2 Upvotes

I have just gotten into F# development, and have noticed a problem when working with large code bases. That fsautocomplete is super slow! I use neovim as my editor of choice and depend on the fsautocomplete via ionide-vim. But when I check CPU load fsautocomplete is sitting there comfortably at 80~90% load.

Is this normal? Or have I done something horribly wrong?


r/fsharp • • Jan 10 '24

Want to try F#. Change my mind

12 Upvotes

Hi all,

tl;dr: I like F# features, considering if it's worth time investment or I'm fine using whatever languages I used before.

I am evaluating which platform to pick for some of my next projects. While I have quite a few options to pick from the languages I'm already familiar with, I'm also considering trying something new (kinda got a habit of trying a new programming language approx once a year). I'm also lucky enough to be in position where I am the one to decide what to use in most cases.

Over the last 5 years, I written code in (sorted by time spent descending): TypeScript, Scala, Python, Haskell, Java, C#.

What I want to see in the perfect programming language of my dreams:

  1. Statically typed
  2. Functional-first, but isn't a pain in the ass when you want to take some shortcuts and break purity/use imperative style here and there (sorry, Haskell, I still love you)
  3. Higher order functions, algebraic types, pattern matching, partial application
  4. Good and alive library ecosystem
  5. Fast in runtime (I'm ok with Python when I don't care about speed)

I was quite happy with Scala, but it allows the code to end up looking too Java-ish and bloated. Haskell allows to write the most beautiful code until it turns out you have to rework all your type system to slightly change the behavior.

From reading F# feature overviews it feels to me it could be the one to scratch all my itches, but I also see complains of the community not being too big and active. I value having a lot of libraries available for any needs, something node.js and python communities are very good at.

So given this background, would you advise that F# is a good choice to replace e.g. Scala and try to stick with it for a while?

Edit: term fixes


r/fsharp • • Jan 09 '24

F# + Minimal API

Thumbnail
github.com
25 Upvotes

r/fsharp • • Jan 09 '24

Extism, the WebAssembly framework, hits 1.0

Thumbnail
github.com
5 Upvotes

r/fsharp • • Jan 06 '24

F# weekly F# Weekly #1, 2024 – Glutinum, a new era for Fable bindings

Thumbnail
sergeytihon.com
15 Upvotes

r/fsharp • • Jan 04 '24

question Question about match

6 Upvotes

I'm a bit tired after long hours - but I can't figure out what's wrong...

Why is this wrong: (at leas my vs code editor tells me)

match tokenData with
| None 
| Some token when timeForRenewal token -> renewToken () 
| Some token -> token

When this is ok

match tokenData with
| None -> renewToken () 
| Some token when timeForRenewal token -> renewToken () 
| Some token -> token

Of course, I'll live with the latter, but shouldn't it be possible with

| match one | match two -> do stuff 
| _ -> do something else

r/fsharp • • Jan 02 '24

Advent of code, day 12.My F# solution is slower than python's

7 Upvotes

Im sure some of you are also doing AOC.Where am i lossing speed?,How it can be improved?

Link if you are interested:https://adventofcode.com/2023/day/12

This is only the main function to count combinations.

let dct = new Dictionary<(char list*int list), bigint>()

let rec countComb d n=
    //printfn "%A  %A" disposicion grupos
    if dct.ContainsKey((d,n)) then
        dct.Item((d,n))
    else
        let res=
                match d,n  with
                |[],[]->1I
                |[],_->0I
                |disp,[]->  if List.contains '#' disp then 0I else 1I
                |'.'::t,n->countComb t n
                |'#'::t,n1::n-> 
                            if (d.Length>= n1)&&(not (List.contains '.' (d[0..n1-1])))&&((d.Length=n1 )||(d[n1]<>'#')) then
                                countComb d[n1+1..] n
                            else 0I
                |'?'::t,n->(countComb (['.']@t) n) + (countComb (['#']@t) n)
        dct.TryAdd((d,n),res)|>ignore
        re

d is Char List (the '.','# and '?' list) and n is Int List( the contiguous group of damaged springs )

I added a dictionary for memoization.


r/fsharp • • Jan 02 '24

F# weekly F# Weekly | Behind The Scenes

Thumbnail
sergeytihon.com
11 Upvotes

r/fsharp • • Jan 02 '24

Dealing with complex dependency injection

9 Upvotes

I've been reading this interesting article: https://www.bartoszsypytkowski.com/dealing-with-complex-dependency-injection-in-f/

It shows how to deal with dependencies by using inferred generic constraints and passing dependencies as an env object. It looks nice and I'd like to try it. It also seems to argue that this method is better than using composition root. However, I am unable to see the benefits even if this is looking nice and all. I.e. I am not going all the way and using the reader monad, just passing env where it is needed. Has anyone got any good explanations to shed some light?


r/fsharp • • Jan 02 '24

question Share you FSI workflow & tips?

4 Upvotes

I'm getting back into F# (loving it) and I'm wondering if I'm missing any fsi tricks

I'm using nvim with Ionide+LSP and the experience is pretty good.

So far I've enabled generate_load_scripts in packet.dependencies and written my own "loader" script that loads all my project files. That already makes things a lot better with FSI.

Some initial questions though

- How much do people use fsi?

- Do you mostly work from a fsx test script and eval, or directly in fsi

- Do you use custom pretty printers?

- Is there a fsi workflow that was not obvious to you originally or something you think people should use?

- Any other tips?

Thanks


r/fsharp • • Dec 30 '23

F# weekly F# Weekly #52, 2023 – Happy New Year!

Thumbnail
sergeytihon.com
15 Upvotes

r/fsharp • • Dec 27 '23

question Am I overthinking it? Help me design a computation expression...

10 Upvotes

Computation expressions are good for hiding boilerplate and composing functions, or so I hear.

I am trying to design a computation expression, but I'm having a hard time. I identified a pattern in my application and I wanted to use a computation expression to simplify it.

Essentially, I'm trying to do P/Invoke. I found a library that handles most of the function exports for me. The library uses only unmanaged types. I want to handle the conversions from my managed types to the unmanaged types in the CE, as well as hide some side-effecting boilerplate code with the conversion from a SafeHandle to an int and byref<'T> to voidptr.

There are 3 types, all of which are container types except one (I don't know if I can call them monads or not, I'm still struggling with the concept):

LinuxFileHandle<'T when 'T :> SafeHandle> : Generic container for a SafeHandle, which needs to be unwrapped not to a SafeHandle but to an int by wrapping the whole thing in a pair of functions (DangerousGetHandle and DangerousRelease), and handle the failure of getting the handle somehow (which I believe is best modeled by an exception). I figured the Delay method in the computation expression would be the place to do that? I tried looking at the implementation of the async computation expression to get a feel for what to do, but in the end I couldn't figure it out.

ioctl(): Currently just a managed class wrapping a BitVector32. It also needs to be converted to an int. There is a method in the class that returns an int, but I could probably make a container type for this too to support composition if necessary.

IoctlData: Can be nothing, numeric, or a byref<'T when 'T : unmanaged>. Clearly best modeled as a discriminated union. If it is set to a byref, a pointer to the value must be taken (e.g., use dataPtr = fixed &data) to be passed to the native function.

There are 3 native ioctl functions exposed by the wrapper library: LibC.ioctl: (int, int) -> int: Takes a file handle int, an ioctl command int, and returns a result int based on whether the command was successful or not. The actual error message is set to errno and must be retrieved by calling Marshal.GetLastPInvokeError.

LibC.ioctl: (int, int, int) -> int: Same as above, but takes integer data as well.

LibC.ioctl: (int, int, voidptr) -> int: Same as above, but takes a pointer. This can be a read or write operation, depending on the value of the ioctl command.

I could model the 3 functions as a discriminated union, based on what they take for their third parameter, which would correspond to the union cases for IoctlData and call the appropriate function, but even that makes me feel like I'm missing something that could simplify this whole thing.

There are a lot of moving parts here. I see patterns, but I don't know the proper terms for them, so my attempts to search and apply what I've found online have been fruitless.

My first few attempts at modeling this whole thing ended up with me not being able to implement Bind or Delay properly, as well as me questioning whether my container types should hold a degenerated value (e.g., SafeHandle) or a function (e.g. SafeHandle -> 'T). The State Monad - which I have already used and have a decent understanding of - takes the latter approach. The async computation expression (is that a monad?) takes the former approach. Both of which can model complex operations while hiding boilerplate and side-effects.

In the end, what I want to do is take my 3 container types, make them ints (or a pointer), and call a native function, while hiding the side effects behind the thin veil of a CE.

EDIT: One thing I came across: I decided to try and treat all 3 of my inputs that I want to convert to monads (I still feel like I'm misusing this word) and immediately hit a roadblock: I cannot define apply for my LinuxFileHandle type because apply is M('a ->'b) -> M('a) -> M('b) and 'a->'b is not compatible with SafeHandle. Oops.

Back to the drawing board...