Monads/List monad: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (syntax highlighting fixup automation)
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(6 intermediate revisions by 5 users not shown)
Line 141:
{{Out}}
<syntaxhighlight lang="applescript">{{3, 4, 5}, {5, 12, 13}, {6, 8, 10}, {7, 24, 25}, {8, 15, 17}, {9, 12, 15}, {12, 16, 20}, {15, 20, 25}}</syntaxhighlight>
 
=={{header|ATS}}==
 
<syntaxhighlight lang="ats">
#include "share/atspre_staload.hats"
 
(* I will use the list type of prelude/SATS/list.sats *)
 
#define NIL list_nil ()
#define :: list_cons
 
fn {a : t@ype}
unit_List (x : a) : list (a, 1) =
x :: NIL
 
fn {a, b : t@ype}
bind_List (m : List a,
f : a -<cloref1> List b) : List0 b =
let
fun
reversed_segments (m : List a,
accum : List0 (List b))
: List0 (List b) =
case+ m of
| NIL => accum
| hd :: tl => reversed_segments (tl, f hd :: accum)
 
fun
assemble_segments (segments : List (List b),
accum : List0 b)
: List0 b =
case+ segments of
| NIL => accum
| hd :: tl =>
let
prval () = lemma_list_param hd
val accum = list_append (hd, accum)
in
assemble_segments (tl, accum)
end
in
assemble_segments (reversed_segments (m, NIL), NIL)
end
 
infixl 0 >>=
overload >>= with bind_List
 
fn
intseq_List {n : nat}
(i0 : int,
n : int n) :<cloref1> list (int, n) =
let
implement
list_tabulate$fopr<int> j = i0 + j
in
list_vt2t (list_tabulate<int> n)
end
 
implement
main0 () =
let
val n = 25
val pythagorean_triples =
intseq_List (1, n) >>=
(lam i =>
(intseq_List (succ (i : int), n) >>=
(lam j =>
(intseq_List (succ (j : int), n) >>=
(lam k =>
let
val i = i : int
and j = j : int
and k = k : int
in
if (i * i) + (j * j) = (k * k) then
@(i, j, k) :: NIL
else
NIL
end)))))
 
fun
loop {n : nat}
.<n>.
(m : list (@(int, int, int), n)) : void =
case+ m of
| NIL => ()
| (@(a, b, c) :: tl) =>
begin
println! ("(", a, ",", b, ",", c, ")");
loop tl
end
in
loop pythagorean_triples
end
</syntaxhighlight>
 
{{out}}
 
We should get a list of some Pythagorean triples that start with some integer between 1 and 25, inclusive.
 
<pre>$ patscc -std=gnu2x -g -O2 -DATS_MEMALLOC_GCBDW list_monad_ats.dats -lgc && ./a.out
(3,4,5)
(5,12,13)
(6,8,10)
(7,24,25)
(8,15,17)
(9,12,15)
(10,24,26)
(12,16,20)
(12,35,37)
(15,20,25)
(15,36,39)
(16,30,34)
(18,24,30)
(20,21,29)
(21,28,35)
(24,32,40)
(24,45,51)
</pre>
 
=={{header|C}}==
Line 182 ⟶ 301:
<syntaxhighlight lang="bash">$ ./monad
13</syntaxhighlight>
 
 
=={{header|C++}}==
Line 610 ⟶ 728:
│5│
└─┘</syntaxhighlight>
 
=={{header|Java}}==
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
 
public final class MonadList {
 
public static void main(String[] aArgs) {
Monad<Integer> integers = Monad.unit(List.of( 2, 3, 4 ));
Monad<String> strings = integers.bind(MonadList::doubler).bind(MonadList::letters);
System.out.println(strings.getValue());
}
private static Monad<Integer> doubler(List<Integer> aList) {
return Monad.unit(aList.stream().map( i -> 2 * i ).toList());
}
private static Monad<String> letters(List<Integer> aList) {
return Monad.unit(aList.stream().map( i -> Character.toString((char) (64 + i)).repeat(i) ).toList());
}
}
 
final class Monad<T> {
public static <T> Monad<T> unit(List<T> aList) {
return new Monad<T>(aList);
}
public <U> Monad<U> bind(Function<List<T>, Monad<U>> aFunction) {
return aFunction.apply(list);
}
public List<T> getValue() {
return list;
}
private Monad(List<T> aList) {
list = new ArrayList<T>(aList);
}
private List<T> list;
}
</syntaxhighlight>
{{ out }}
<pre>
[DDDD, FFFFFF, HHHHHHHH]
</pre>
 
=={{header|Javascript}}==
Line 692 ⟶ 861:
 
<pre>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [7, 24, 25], [8, 15, 17], [9, 12, 15], [12, 16, 20], [15, 20, 25]]</pre>
 
=={{header|jq}}==
{{works with|jq}}
''Also works with gojq and fq'' modulo the proviso about "::"
 
In this entry, we adopt the approach described in the Wikipedia article on monads
at [https://en.wikipedia.org/wiki/Monad_(functional_programming)], specifically:
<pre>
"A monad can be created by defining a type constructor M and two operations:
 
return :: a -> M a (often also called unit), which receives a value of type a and wraps it into a monadic value of type M a,
and
bind :: (M a) -> (a -> M b) -> (M b)
which receives a function f over type a and can transform monadic values m a applying f to the unwrapped value a,
returning a monadic value M b"
</pre>
 
In the following, the monadic type `a` can be specified as any JSON
value, but for the List monad, it is just "List". Choosing a string has the advantage
that we can use jq's support for function names of the form
`Namespace::identifier` to give convenient names to the "return" and
"bind" functions for the List monad, namely `List::return` and
`List::bind`.
 
Since gojq does not currently support the definition of functions
with a Namespace prefix, the following would have to be adapted; one
possibility wold be to replace occurrences of `::` in function names
by `__`.
 
Notice that the "return" and "bind" wrappers for List (i.e., `List::return` and
`List::bind`) can be tailored to the List monad independently of the
wrapper definitions for other monads.
<syntaxhighlight lang=jq>
# Constructor:
def Monad($type; $value):
{class: "Monad", $type, $value};
 
# Is the input a monad of type $Type?
def is_monad($Type):
(type == "object")
and (.class == "Monad")
and (.type == $Type) ;
 
# input: a value consistent with the "List" monadic type (in practice, a JSON array)
# No checking is done here as the monadic type system is outside the scope of this entry.
def List::return:
Monad("List"; .);
def List::bind(f):
if is_monad("List")
then .value |= f
else error("List::bind error: monadic type of input is \(.type)")
end;
 
# Two illustrative operations on JSON arrays
def increment: map(. + 1);
def double: map(. * 2);
def ml1:
[3, 4, 5] | List::return;
def ml2:
ml1 | List::bind(increment) | List::bind(double);
 
"\(ml1.value) -> \(ml2.value)"
</syntaxhighlight>
{{output}}
<pre>
[3,4,5] -> [8,10,12]
</pre>
 
 
=={{header|Julia}}==
Line 897 ⟶ 1,136:
=={{header|Python}}==
 
<syntaxhighlight lang="python">"""A List Monad. Requires Python >= 3.7 for type hints."""
"""A List Monad. Requires Python >= 3.7 for type hints."""
from __future__ import annotations
from itertools import chain
 
from typing import Any
from typing import Callable
from typing import Iterable
Line 909 ⟶ 1,148:
 
T = TypeVar("T")
U = TypeVar("U")
 
 
Line 916 ⟶ 1,156:
return cls(value)
 
def bind(self, func: Callable[[T], MList[AnyU]]) -> MList[AnyU]:
return MList(chain.from_iterable(map(func, self)))
 
def __rshift__(self, func: Callable[[T], MList[AnyU]]) -> MList[AnyU]:
return self.bind(func)
 
 
if __name__ == "__main__":
# Chained int and string functions.
print(
MList([1, 99, 4])
Line 938 ⟶ 1,178:
)
 
# Cartesian product of [1..5] and [6..10].
print(
MList(range(1, 6)).bind(
Line 945 ⟶ 1,185:
)
 
# Pythagorean triples with elements between 1 and 25.
print(
MList(range(1, 26)).bind(
Line 1,136 ⟶ 1,376:
[3,4,5].bind_comp(listy_doub, listy_inc) #=> [8, 10, 12]
</syntaxhighlight>
=={{header|Swift}}==
 
The unit/return function is provided by the constructor for a Swift array. I define a unit function simply to keep the terminology straight. Similarly, the flatmap function provides what we need for bind, but I define a bind function explicitly.
 
I also define an operator that is the same as bind but which makes chaining easier.
 
My two functions to use are one that retiurns the two number adjacent to the supplied Int and another that returns the square roots (as Double) of an Int if it is positive or an empty list, if it is negative.
 
<syntaxhighlight lang="Swift">
precedencegroup MonadPrecedence {
higherThan: BitwiseShiftPrecedence
associativity: left
}
 
infix operator >>-: MonadPrecedence // Monadic bind
 
extension Array
{
static func unit(_ x: Element) -> [Element]
{
return [x]
}
 
func bind<T>(_ f: (Element) -> [T]) -> [T]
{
return flatMap(f)
}
 
static func >>- <U>(_ m: [Element], _ f: (Element) -> [U]) -> [U]
{
return m.flatMap(f)
}
}
 
func adjacent(_ x: Int) -> [Int]
{
[x - 1, x + 1]
}
 
func squareRoots(_ x: Int) -> [Double]
{
guard x >= 0 else { return [] }
return [Double(x).squareRoot(), -(Double(x).squareRoot())]
}
 
print("\([Int].unit(8).bind(adjacent).bind(squareRoots))")
print("\([Int].unit(8) >>- adjacent >>- squareRoots)")
print("\([Int].unit(0) >>- adjacent >>- squareRoots)")
</syntaxhighlight>
{{out}}
<pre>
[2.6457513110645907, -2.6457513110645907, 3.0, -3.0]
[2.6457513110645907, -2.6457513110645907, 3.0, -3.0]
[1.0, -1.0]
</pre>
 
=={{header|uBasic/4tH}}==
Line 1,157 ⟶ 1,452:
=={{header|Wren}}==
{{trans|Go}}
<syntaxhighlight lang="ecmascriptwren">class Mlist {
construct new(value) { _value = value }
 
9,476

edits