Monads/List monad: Difference between revisions

no edit summary
m (syntax highlighting fixup automation)
No edit summary
Line 1,136:
[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}}==
19

edits