DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • In-Depth Guide to Using useMemo() Hook in React
  • Yet 4 More Techniques for Writing Better Java
  • Revolutionizing Network Operations With Automated Solutions: A Deep Dive Into ReactJS
  • The ABCs of Unity's Coroutines: From Basics to Implementation

Trending

  • Endpoint Security Controls: Designing a Secure Endpoint Architecture, Part 1
  • Unmasking Entity-Based Data Masking: Best Practices 2025
  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Unlocking Data with Language: Real-World Applications of Text-to-SQL Interfaces
  1. DZone
  2. Coding
  3. Languages
  4. Closure-based State in F#

Closure-based State in F#

How to use F# to store state in object or class fields.

By 
Ted Neward user avatar
Ted Neward
·
Apr. 29, 16 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
12.2K Views

Join the DZone community and get the full member experience.

Join For Free

Being an object/functional hybrid language, F# offers the opportunity to support either a traditional object-field approach to encapsulating state, as well as the more “functional” style of Closure-based State. As such, developers will generally prefer to store state in object/class fields, but there can still be situations where encapsulating the state away from the object as a whole can be preferable.

However, F# has some interesting language restrictions around enclosed bound variables; specifically, because F# wants to assume that all bound values are immutable by default, F# will require a slight amendment to the enclosed local state, marking it as a “reference” (using the ref keyword), before it can be used inside of a returned function:

let operation =
    let state = ref 100
    fun adjust ->
        state := (!state) + adjust

Thanks to F#’s “last expression in an expression block is the assumed return value” feature, making use of this feels absolutely trivial; the anonymous function receiving the single parameter adjust is assigned to the local value operation, meaning that now operation will be operating on the referenced state value, but without any sort of opportunity for any other operation or library to modify state.

When working with objects this gets trickier, since F# (like its kin C# and Visual Basic) is a strongly-typed language, and as such wants clients to have compile-time awareness of the object types they are invoking. Thus, the typical idiomatic usage for F# here will be to use Closure-based State to implement an anonymous implementation of an interface, and have the outer function declared to return an instance of such. This is trivial to do with object expressions:

type IInterface =
    interface
        abstract Operation: (int) -> int
    end

let instance =
    let state = ref 100
    { new IInterface with
        member x.Operation(adjust) = 
            state := (!state) + adjust
            !state
    }

let result = instance.Operation(100)
printfn "%A" result

Alternatively, F# can return an instance of a ; this is somewhat contradictory to the spirit of the F# language, since it is strongly-typed by nature, but circumstances will sometimes suggest it as useful, depending (as always) on the context.

Object (computer science) dev Blocks Library Sort (Unix) Interface (computing) Implementation

Published at DZone with permission of Ted Neward, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • In-Depth Guide to Using useMemo() Hook in React
  • Yet 4 More Techniques for Writing Better Java
  • Revolutionizing Network Operations With Automated Solutions: A Deep Dive Into ReactJS
  • The ABCs of Unity's Coroutines: From Basics to Implementation

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!