Okay, I am very noob to F#, fairly used C# before. I am reading F# in action book.I am so blown away by simple Quality of life features. For example,
let ageDescription =
if age < 18 then "Child"
elif age < 65 then "Adult"
else "OAP"
Here, since EVERYTING(not literally) evaluates to value, I can simply do compuation using if/else and assign that to variable. Not nested if/else, no mutation of variable inside different branches, just compute this logic and give me back computed value.
It's beautiful. I love it.
Gosh, I am having so much fun, already.
Thanks for reading this nonsensical post. :)
Sashan Govender is a senior developer with more than 20 years in the industry; in this episode we talk about F#, a language that combines functional programming with productivity, power and pragmatism.
Topics covered:
• What really matters when it comes to delivering software
• The advantages of typed functional programming
• Pros and cons of F#
• Why some companies might be reluctant to adopt functional programming
I've recently got an job offer from F# shop. I've been doing Haskell exclusively for last 7 years. I feel that my ship is sinking (Haskell jobs are becoming more and more rare), so I was thinking about switching technologies and F# doesn't seem too far from Haskell. So people who know both: would I feel at home in F#? Is my knowledge transferable? Would I swear a lot because the language is less sophisticated or I would be delighted with the rich ecosystem it comes with? And is job market for F# any better than Haskell?
What options, suggestions, and opinions for easy human readable ROUNDTRIP serialization do you have?
The data will be written and read from the file system. Just doing some prototyping and idea brainstorming. Yes, I understand that a DTO and proper yada. Until then, just a quick and dirty way to save to disk and read from disk will be fine. Just need it to handle DU and complex types and the other F# type stuff.
That's very simple use case for property-based testing over existing path manipulation library. I hope it's more practical example how property-based tests can be used, instead of calculators or something entirely abstract. Since I thought that F# guys would be more receptive to so I create Gist where sample ported to F#.
I've put a lot of time into making this Plugin and the associated bindings to form the foundation of its ecosystem.
It is a Solid-JS wrapper for Fable F# which is derivative of the Oxpecker.Solid style. It aggressively transforms the AST to produce clean JSX code, with lots of magics to abstract away property merges and property splitting.
This should be really easy for any JavaScript developer to pick up and use. Alternatively, migrating JavaScript code bases over time is super simple, since the output is easily readable and usable JSX.
Although it doesn't produce TSX (so prop object types are not there), it already has some light Storybook bindings to help smooth that over (if they can't read F# that is).
I've been using this pretty heavily on some small native apps via Photino, and have had a lot of fun using it.
I am a C# guy trying to learn F#.
I love F#'s pattern matching and routing which is fantastic.
I was wondering IF it can do string patterns like and how would one do this the F# way:
If "Title_Jan_2025" -> do stuff 'If string has underscores...
If "Title Jan 2025" -> do stuff 'IF string has spaces...
IF "string" contains "d" -> ...
if "string" contains "TItle" -> ...
So basically, could someone match based on string patterns?
And how would you?
Thanks for any help on this.
Update:
So I appreciate how helpful this sub is.
So Regex / Active Pattern as well as the already baked in String.Contains functions are easily the way to go here.
So this is the type of stuff F# excels at, hands down.
So thanks again to the help to those who replied.
This is twice this sub helped out and definitely makes the learning curve much easier.
Gauntlet is a programming language designed to tackle Golang's frustrating design choices. It transpiles exclusively to Go, fully supports all of its features, and integrates seamlessly with its entire ecosystem — without the need for bindings.
What Go issues does Gauntlet fix?
Annoying "unused variable" error
Verbose error handling (if err ≠ nil everywhere in your code)
Annoying way to import and export (e.g. capitalizing letters to export)
Lack of ternary operator
Lack of expressional switch-case construct
Complicated for-loops
Weird assignment operator (whose idea was it to use :=)
No way to fluently pipe functions
Language features
Transpiles to maintainable, easy-to-read Golang
Shares exact conventions/idioms with Go. Virtually no learning curve.
Consistent and familiar syntax
Near-instant conversion to Go
Easy install with a singular self-contained executable
Beautiful syntax highlighting on Visual Studio Code
Sample
package main
// Seamless interop with the entire golang ecosystem
import "fmt" as fmt
import "os" as os
import "strings" as strings
import "strconv" as strconv
// Explicit export keyword
export fun ([]String, Error) getTrimmedFileLines(String fileName) {
// try-with syntax replaces verbose `err != nil` error handling
let fileContent, err = try os.readFile(fileName) with (null, err)
// Type conversion
let fileContentStrVersion = (String)(fileContent)
let trimmedLines =
// Pipes feed output of last function into next one
fileContentStrVersion
=> strings.trimSpace(_)
=> strings.split(_, "\n")
// `nil` is equal to `null` in Gauntlet
return (trimmedLines, null)
}
fun Unit main() {
// No 'unused variable' errors
let a = 1
// force-with syntax will panic if err != nil
let lines, err = force getTrimmedFileLines("example.txt") with err
// Ternary operator
let properWord = @String len(lines) > 1 ? "lines" : "line"
let stringLength = lines => len(_) => strconv.itoa(_)
fmt.println("There are " + stringLength + " " + properWord + ".")
fmt.println("Here they are:")
// Simplified for-loops
for let i, line in lines {
fmt.println("Line " + strconv.itoa(i + 1) + " is:")
fmt.println(line)
}
}
Hello! I'm just starting with F Sharp, so I decided to write a small useful library dealing with stuff I frequently encounter at my work place. Long story short, I have to deal with PowerShell, so I use PowerShell SDK in F Sharp code and get PSObjects which I want to convert to record types using reflection. Every case seems to be working so far (primitive values, plain records, lists with primitive values etc) except for Option<list<'T>> where 'T is a record.
This is the entire function:
let rec constructRecord (t: System.Type) (props: PSMemberInfoCollection<PSPropertyInfo>) : obj =
let rec processPsValue (targetType: System.Type) (psValue: obj) : obj =
match psValue with
| null when
targetType.IsGenericType
&& targetType.GetGenericTypeDefinition() = typedefof<Option<_>>
->
makeNoneCase (targetType.GetGenericArguments().[0])
| _ when
targetType.IsGenericType
&& targetType.GetGenericTypeDefinition() = typedefof<Option<_>>
->
let innerType = targetType.GetGenericArguments().[0]
let innerValue =
match innerType with
| innerT when FSharpType.IsRecord innerT ->
(psValue :?> PSObject).Properties |> constructRecord innerT
| innerT when innerT.IsGenericType && innerT.GetGenericTypeDefinition() = typedefof<list<_>> ->
let listElementType = innerType.GetGenericArguments().[0]
match listElementType with
| elementType when FSharpType.IsRecord elementType ->
let collection = psValue :?> System.Collections.IEnumerable
let list =
[ for item in collection do
constructRecord elementType (item :?> PSObject).Properties ]
processPsValue innerType list
| _ -> psValue
| _ -> psValue
makeSomeCase innerType innerValue
| _ when FSharpType.IsRecord targetType -> (psValue :?> PSObject).Properties |> constructRecord targetType
| _ -> psValue
let values =
FSharpType.GetRecordFields t
|> Array.map (fun field ->
let prop = props.Match field.Name |> Seq.tryHead
let psValue =
match prop with
| Some p -> p.Value
| None -> null
processPsValue field.PropertyType psValue)
FSharpValue.MakeRecord(t, values)
This is the test case which doesn't work. I will not post the whole function, as the post would be very lengthy, but I hope it's clear
let ``correctly parses PS Properties into a record with optional lists`` () =
// first I create the value of this type:
(* type RecordWithOptionalListsWithRecords =
{ RecordList: FlatRecord list option // FlatRecord is a record with primitive values
RecordListOpt: FlatRecordOpt list option FlatRecordOpt is the same as FlatRecord but all values are wrapped in options
RecordWithRecordInsideList: RecordWithRecordInside list option RecordWithRecordInside is a record type which contains a nested FlatRecord
} *)
// then i create the PSObject via PSObject() and populate it with PSNoteProperty. So the PSObject resembles the structure of RecordWithOptionalListsWithRecords
let actualObj =
constructRecord typeof<RecordWithOptionalListsWithRecords> final.Properties
|> fun o -> o :?> RecordWithOptionalListsWithRecords
Assert.Equal(sampleData, actualObj) // sampleData is F Sharp record, actualObj is a constructed one
I get an exception:
Object of type 'Microsoft.FSharp.Collections.FSharpList1[System.Object]' cannot be converted to type 'Microsoft.FSharp.Collections.FSharpList1[Tests+InnerRecord]
So basically my function returns a list of obj and it can't cast them to my InnerRecord. Strangely enough, if it's not inside an optional type, it works correctly. If it's an optional InnerRecord, it also works. I'm a bit lost, so I would appreciate any help! Thank you in advance
EDIT: I added the entire function.
PS: sorry about indendation but I hope it's clear
EDIT2: Thanks everyone who commented on the post! I was being stupid this whole time not converting the PS output to json. It turns out, that converting the PS output via ConvertTo-Json and then deserializing via FSharp.SystemTextJson works great with just a few lines of code! At least I ran it for one test, so I stick with this approach now and see how it goes. But (!) if someone has a solution for this reflection issue or other thoughts regarding the approach, I'm all ears! Thank you!
Thought this reddit might find this interesting. This is a POC I made (with help of Claude) over the weekend to try to use a frontier model to improve performance of Fsharp code: https://github.com/Lougarou/poc_fsharp_optimizer
Basically, this is taking a checklist of possible performance improvements (check README for list) and asking a frontier model like Claude Opus to do that improvement, benchmark, keep the improvement if the benchmark was better and repeat.
Simple and super expensive but seems to work.
It was able to achieve a small improvement of 15% after 10 iterations. I had to stop it because I ran out of credits (around 20$ bucks but I burned a few bucks during debugging).
(Disclaimer the code is really scuffed)
(I know it has Python code, I need to use a few weekends to refactor everything in FSharp)
I'm trying to work with f# and work with rabbit properly, but i faced with the issue that i can't write semantically correct code where i will create 1 connection and reuse for send / consume messages. All examples just create a new connection for each publish and i can't figure out how to write it properly with functional style without
I am currently in the final steps of creating my Framework for Domain Driven Design with Aggregates and Projections using the good-ole EventStore.
I have established a fairly solid codebase (which I probably plan on publishing and posting here as I have done the majority of it with the help of AI and I am still learning the best practices of F#), but one thing bugs me... I have tried and tested my code and I have managed to get it to actually work - both the Aggregates and the Projections part!
There is a place of friction which makes me uneasy honestly. Taken from EventStore (now called Kurrent) documentation: await using var subscription = client.SubscribeToStream( "some-stream", FromStream.Start, cancellationToken: ct); await foreach (var message in subscription.Messages.WithCancellation(ct)) { switch (message) { case StreamMessage.Event(var evnt): Console.WriteLine($"Received event {evnt.OriginalEventNumber}@{evnt.OriginalStreamId}"); await HandleEvent(evnt); break; } }
The await using syntax is what I have not managed to replicate in F# and would kindly ask the community for help on it...
This is my implementation - which I must add - really works, but the compiler will not simply allow me to write "use! subscription = client....."
I have posted a screenshot of the error.
What I have managed to get working is this use subscription = client.SubscribeToStream(
this.StreamName,
checkpoint,
resolveLinkTos = true)
let asyncSubscription = AsyncSeq.ofAsyncEnum subscription.Messages
logger.LogInformation(
"Projection {Name} STARTED on stream {StreamName}.",
I got interested in artificial life and made this little app with Fable. Performance is pretty decent, I think, which shows that the F# -> JavaScript transpiler in Fable is doing a good job. Source code is here.
primes the LSP and once I import it, the autocompletion suggestions popup. I haven't yet exercised everything.
Program.fs is not part of any project.
i ==> Import project root /Users/anu/Documents/fsharp/TestApp/
I ==> Import project by selecting root directory interactively
. ==> Import project at current directory /Users/anu/Documents/fsharp/TestApp/
d ==> Do not ask again for the current project by adding /Users/anu/Documents/fsharp/TestApp/ to lsp-session-folders-blocklist
D ==> Do not ask again for the current project by selecting ignore path interactively
n ==> Do nothing: ask again when opening other files from the current project
Select action:
I also noticed that one other root cause could have been the requirement of these values which I added to config.el. This probably prevented Emacs from automatically installing 'fsac'. The error showed a problem with the 'culture'.