Monads/List monad: Difference between revisions
→{{header|AppleScript}}: Some simplification - normalised argument sequence in a couple of higher-order functions
(→{{header|AppleScript}}: Some simplification - normalised argument sequence in a couple of higher-order functions) |
|||
Line 15:
We can use a list monad in AppleScript to express set comprehension for the Pythagorean triples, but the lack of nestable first class (and anonymous) functions means that the closure can only be achieved using script objects, which makes the idiom rather less direct and transparent. AppleScript is creaking at the seams here.
<lang AppleScript>on run
-- Pythagorean triples drawn from integers in the range [1..n]
-- {(x, y, z) | x <- [1..n], y <- [x+1..n], z <- [y+1..n], (x^2 + y^2 = z^2)}
Line 27 ⟶ 25:
end run
-- pythagoreanTriples :: Int -> [(Int, Int, Int)]
on pythagoreanTriples(maxInteger)
script
script lambdaY
on
if x * x + y * y = z * z then▼
end lambdaX▼
end
end script
end script
▲ if x * x + y * y = z * z then
▲ return my unit([x, y, z])
else▼
return []▼
end if▼
bind(lambdaY, range(1 + x, maxInteger))
end lambdaZ▼
end script
end pythagoreanTriples
--
-- Monadic bind for lists is simply ConcatMap
-- which applies a function f directly to each value in the list,
-- and returns the set of results as a concat-flattened list
-- [a] -> (a -> [b]) -> [b]▼
script concat▼
foldl(concat, {}, map(f, xs))
end bind
-- Monadic return/unit/inject for lists: just wraps a value in a list
-- a -> [a]
on unit(a)
Line 76 ⟶ 78:
end unit
▲-- [a] -> (a -> b) -> [b]
-- GENERIC LIBRARY FUNCTIONS
▲on map(xs, f)
set mf to mReturn(f)
set lng to length of xs
Line 87 ⟶ 92:
end map
--
on foldl(f, startValue, xs)
set mf to mReturn(f)
Line 103:
end repeat
return v
end
--
on
else
set end of lst to i
▲ script
end repeat
▲ property lambda : f
-- Script | Handler -> Script
Line 130 ⟶ 129:
end if
end mReturn
▲on range(m, n)
▲ set base to m - 1
▲ set lst to {}
▲ repeat with i from 1 to lng
▲ set end of lst to i + base
▲ end repeat
</lang>
Line 146 ⟶ 134:
{{Out}}
<
=={{header|Clojure}}==
|