Pascal's triangle: Difference between revisions

→‎{{header|AppleScript}}: Slight simplification - closure by direct nesting
(→‎{{header|AppleScript}}: Slight simplification - closure by direct nesting)
Line 279:
 
<lang AppleScript>
-- pascal :: Int -> [[Int]]
 
on pascal(intRows)
on run
-- addRow [[Int]] -> [[Int]]
set lstTriangle to pascal(7)
script addRow
-- nextRow :: [Int] -> [Int]
on nextRow(row)
-- add :: Int -> Int -> Int
script add
on lambda(a, b)
a + b
end lambda
end script
zipWith(add, [0] & row, row & [0])
end nextRow
on lambda(xs)
xs & {nextRow(item -1 of xs)}
end lambda
end script
foldl(addRow, {{1}}, range(1, intRows - 1))
intercalate(linefeed, ¬
map(mClosure(spacedAndIndented, ¬
{lngWidth:(length of intercalate(" ", (item -1 of lstTriangle)))}), ¬
lstTriangle))
end run
 
 
-- Argument: number of Pascal's triangle rows
 
-- pascal :: Int -> [[Int]]
on pascal(n)
foldl(my addRow, {{1}}, range(1, n - 1))
end pascal
 
-- addRow [[Int]] -> [[Int]]
on addRow(lst)
lst & {nextRow(item -1 of lst)}
end addRow
 
-- TEST
-- nextRow :: [Int] -> [Int]
on nextRow(row)
zipWith(my add, [0] & row, row & [0])
end nextRow
 
on run
-- add :: Int -> Int -> Int
set lstTriangle to pascal(7)
on add(a, b)
a + b
script spacedAndIndented
end add
property width : (length of intercalate(" ", (item -1 of lstTriangle)))
 
 
-- [Text | Number] -> Text
 
on lambda(lst)
-- TESTING
set strLine to intercalate(" ", lst)
 
nreps(space, width - ((length of strLine) / 2)) & strLine
-- [Text | Number] -> Text
end lambda
on spacedAndIndented(lst)
end script
set strLine to intercalate(" ", lst)
nreps(space, ¬
((my closure's lngWidth) - (length of strLine)) / 2) & strLine
end spacedAndIndented
 
 
-- String -> Int -> String
on nreps(s, n)
set o to ""
if n < 1 then return o
intercalate(linefeed, map(spacedAndIndented, lstTriangle))
repeat while (n > 1)
end run
if (n mod 2) > 0 then set o to o & s
set n to (n div 2)
set s to (s & s)
end repeat
return o & s
end nreps
 
 
 
-- GENERIC LIBRARY FUNCTIONS
 
 
-- foldl :: (a -> b -> a) -> a -> [b] -> a
Line 377 ⟶ 361:
return lst
end map
 
-- String -> Int -> String
on nreps(s, n)
set o to ""
if n < 1 then return o
repeat while (n > 1)
if (n mod 2) > 0 then set o to o & s
set n to (n div 2)
set s to (s & s)
end repeat
return o & s
end nreps
 
 
Line 401 ⟶ 398:
-- mReturn :: Handler -> Script
on mReturn(f)
if class of f is script then return f
script f
else
property lambda : f
end script
property lambda : f
end mReturn
end script
 
end if
-- Handler -> Record -> Script
end mReturn</lang>
on mClosure(f, recBindings)
script
property closure : recBindings
property lambda : f
end script
end mClosure
</lang>
 
 
9,655

edits