How to resolve the algorithm Monads/List monad step by step in the Wren programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Monads/List monad step by step in the Wren programming language

Table of Contents

Problem Statement

A Monad is a combination of a data-type with two helper functions written for that type. The data-type can be of any kind which can contain values of some other type – common examples are lists, records, sum-types, even functions or IO streams. The two special functions, mathematically known as eta and mu, but usually given more expressive names like 'pure', 'return', or 'yield' and 'bind', abstract away some boilerplate needed for pipe-lining or enchaining sequences of computations on values held in the containing data-type. The bind operator in the List monad enchains computations which return their values wrapped in lists. One application of this is the representation of indeterminacy, with returned lists representing a set of possible values. An empty list can be returned to express incomputability, or computational failure. A sequence of two list monad computations (enchained with the use of bind) can be understood as the computation of a cartesian product. The natural implementation of bind for the List monad is a composition of concat and map, which, used with a function which returns its value as a (possibly empty) list, provides for filtering in addition to transformation or mapping.

Demonstrate in your programming language the following:

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Monads/List monad step by step in the Wren programming language

Source code in the wren programming language

class Mlist {
    construct new(value) { _value = value }

    value { _value }

    bind(f) { f.call(_value) }

    static unit(lst) { Mlist.new(lst) }
}

var increment = Fn.new { |lst|
    var lst2 = lst.map { |v| v + 1 }.toList
    return Mlist.unit(lst2)
}

var double = Fn.new { |lst|
    var lst2 = lst.map { |v| v * 2 }.toList
    return Mlist.unit(lst2)
}

var ml1 = Mlist.unit([3, 4, 5])
var ml2 = ml1.bind(increment).bind(double)
System.print("%(ml1.value) -> %(ml2.value)")

  

You may also check:How to resolve the algorithm Greatest common divisor step by step in the PL/I programming language
You may also check:How to resolve the algorithm Even or odd step by step in the 11l programming language
You may also check:How to resolve the algorithm Gray code step by step in the Phix programming language
You may also check:How to resolve the algorithm Mutual recursion step by step in the x86 Assembly programming language
You may also check:How to resolve the algorithm Population count step by step in the PureBasic programming language