Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 746749
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T14:07:35+00:00 2026-05-14T14:07:35+00:00

What would an equivalent construct of a monad be in Ruby?

  • 0

What would an equivalent construct of a monad be in Ruby?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T14:07:36+00:00Added an answer on May 14, 2026 at 2:07 pm

    The precise technical definition: A monad, in Ruby, would be any class with bind and self.unit methods defined such that for all instances m:

    m.class.unit[a].bind[f] == f[a]
    m.bind[m.class.unit] == m  
    m.bind[f].bind[g] == m.bind[lambda {|x| f[x].bind[g]}]
    

    Some practical examples

    A very simple example of a monad is the lazy Identity monad, which emulates lazy semantics in Ruby (a strict language):

    class Id
      def initialize(lam)
        @v = lam
      end
    
      def force
        @v[]
      end
    
      def self.unit
        lambda {|x| Id.new(lambda { x })}
      end
    
      def bind
        x = self
        lambda {|f| Id.new(lambda { f[x.force] })}
      end
    end
    

    Using this, you can chain procs together in a lazy manner. For example, in the following, x is a container “containing” 40, but the computation is not performed until the second line, evidenced by the fact that the puts statement doesn’t output anything until force is called:

    x = Id.new(lambda {20}).bind[lambda {|x| puts x; Id.unit[x * 2]}]
    x.force
    

    A somewhat similar, less abstract example would be a monad for getting values out of a database. Let’s presume that we have a class Query with a run(c) method that takes a database connection c, and a constructor of Query objects that takes, say, an SQL string. So DatabaseValue represents a value that’s coming from the database. DatabaseValue is a monad:

    class DatabaseValue
      def initialize(lam)
        @cont = lam
      end
    
      def self.fromQuery(q)
        DatabaseValue.new(lambda {|c| q.run(c) })
      end
    
      def run(c)
        @cont[c]
      end
    
      def self.unit
        lambda {|x| DatabaseValue.new(lambda {|c| x })}
      end
    
      def bind
        x = self
        lambda {|f| DatabaseValue.new(lambda {|c| f[x.run(c)].run(c) })}
      end
    end
    

    This would let you chain database calls through a single connection, like so:

    q = unit["John"].bind[lambda {|n|
      fromQuery(Query.new("select dep_id from emp where name = #{n}")).
        bind[lambda {|id|
          fromQuery(Query.new("select name from dep where id = #{id}"))}].
            bind[lambda { |name| unit[doSomethingWithDeptName(name)] }]
    
    begin
      c = openDbConnection
      someResult = q.run(c)
    rescue
      puts "Error #{$!}"
    ensure
      c.close
    end
    

    OK, so why on earth would you do that? Because there are extremely useful functions that can be written once for all monads. So code that you would normally write over and over can be reused for any monad once you simply implement unit and bind. For example, we can define a Monad mixin that endows all such classes with some useful methods:

    module Monad
      I = lambda {|x| x }
    
      # Structure-preserving transform that applies the given function
      # across the monad environment.
      def map
        lambda {|f| bind[lambda {|x| self.class.unit[f[x]] }]}
      end
    
      # Joins a monad environment containing another into one environment.
      def flatten
        bind[I]
      end
    
      # Applies a function internally in the monad.
      def ap
        lambda {|x| liftM2[I,x] }
      end
    
      # Binds a binary function across two environments.
      def liftM2
        lambda {|f, m|
          bind[lambda {|x1|
            m.bind[lambda {|x2|
              self.class.unit[f[x1,x2]]
            }]
          }]
        }
      end
    end
    

    And this in turn lets us do even more useful things, like define this function:

    # An internal array iterator [m a] => m [a]
    def sequence(m)
      snoc = lambda {|xs, x| xs + [x]}
      lambda {|ms| ms.inject(m.unit[[]], &(lambda {|x, xs| x.liftM2[snoc, xs] }))}
    end
    

    The sequence method takes a class that mixes in Monad, and returns a function that takes an array of monadic values and turns it into a monadic value containing an array. They could be Id values (turning an array of Identities into an Identity containing an array), or DatabaseValue objects (turning an array of queries into a query that returns an array), or functions (turning an array of functions into a function that returns an array), or arrays (turning an array of arrays inside-out), or parsers, continuations, state machines, or anything else that could possibly mix in the Monad module (which, as it turns out, is true for almost all data structures).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 381k
  • Answers 381k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Do you have any jobs running on a timed basis… May 14, 2026 at 10:19 pm
  • Editorial Team
    Editorial Team added an answer The web.config file is an XML file, so your only… May 14, 2026 at 10:19 pm
  • Editorial Team
    Editorial Team added an answer Is it really true? and if so does anyone know… May 14, 2026 at 10:19 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.