Catamorphism: Difference between revisions

Content added Content deleted
(→‎{{header|AppleScript}}: Primitive and output updated)
Line 248: Line 248:
(Note that to obtain first-class functions from user-defined AppleScript handlers, we have to 'lift' them into script objects).
(Note that to obtain first-class functions from user-defined AppleScript handlers, we have to 'lift' them into script objects).


<lang AppleScript>-- CATAMORPHISMS --------------------------------------------------
<lang AppleScript>

---------------------- CATAMORPHISMS ---------------------


-- the arguments available to the called function f(a, x, i, l) are
-- the arguments available to the called function f(a, x, i, l) are
Line 287: Line 289:




-- OTHER FUNCTIONS DEFINED IN TERMS OF FOLDL AND FOLDR ------------
--- OTHER FUNCTIONS DEFINED IN TERMS OF FOLDL AND FOLDR --


-- concat :: [[a]] -> [a] | [String] -> String
-- concat :: [String] -> string
on concat(xs)
on concat(xs)
script append
foldl(my append, "", xs)
on |λ|(a, b)
a & b
end |λ|
end script
if length of xs > 0 and class of (item 1 of xs) is string then
set unit to ""
else
set unit to {}
end if
foldl(append, unit, xs)
end concat
end concat



-- product :: Num a => [a] -> a
-- product :: Num a => [a] -> a
Line 315: Line 307:
foldr(result, 1, xs)
foldr(result, 1, xs)
end product
end product


-- str :: a -> String
on str(x)
x as string
end str



-- sum :: Num a => [a] -> a
-- sum :: Num a => [a] -> a
Line 328: Line 327:




-- TEST -----------------------------------------------------------
--------------------------- TEST -------------------------
on run
on run
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
set xs to {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
{sum(xs), product(xs), concat(xs)}
{sum(xs), product(xs), concat(map(str, xs))}
--> {55, 3628800, "10987654321"}
--> {55, 3628800, "10987654321"}
Line 338: Line 337:




-- GENERIC FUNCTION -----------------------------------------------
--------------------- GENERIC FUNCTION -------------------

-- append :: String -> String -> String
on append(a, b)
a & b
end append


-- map :: (a -> b) -> [a] -> [b]
on map(f, xs)
-- The list obtained by applying f
-- to each element of xs.
tell mReturn(f)
set lng to length of xs
set lst to {}
repeat with i from 1 to lng
set end of lst to |λ|(item i of xs, i, xs)
end repeat
return lst
end tell
end map



-- Lift 2nd class handler function into 1st class script wrapper
-- Lift 2nd class handler function into 1st class script wrapper
Line 352: Line 372:
end mReturn</lang>
end mReturn</lang>
{{out}}
{{out}}
<pre>{55, 3628800, "10987654321"}</pre>
<pre>{55, 3628800, "12345678910"}</pre>


=={{header|Arturo}}==
=={{header|Arturo}}==