Permutations with repetitions: Difference between revisions
Content added Content deleted
(Applescript →Strict evaluation of the whole set: updated) |
(→Applescript lazy evaluation: pruned a redundant function, edited a sub-title) |
||
Line 96: | Line 96: | ||
<lang AppleScript>{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</lang> |
<lang AppleScript>{{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}, {3, 1}, {3, 2}, {3, 3}}</lang> |
||
=== |
===Lazy evaluation with a generator=== |
||
Permutations with repetition by treating the <math>n^k</math> elements as an ordered set, and writing a function from a zero-based index to the nth permutation. This allows us terminate a repeated generation on some condition, or explore a sub-set without needing to generate the whole set: |
Permutations with repetition by treating the <math>n^k</math> elements as an ordered set, and writing a function from a zero-based index to the nth permutation. This allows us terminate a repeated generation on some condition, or explore a sub-set without needing to generate the whole set: |
||
<lang AppleScript>use AppleScript version "2.4" |
<lang AppleScript>use AppleScript version "2.4" |
||
Line 254: | Line 254: | ||
return out & dbl |
return out & dbl |
||
end replicate |
end replicate |
||
-- take :: Int -> [a] -> [a] |
|||
-- take :: Int -> String -> String |
|||
on take(n, xs) |
|||
set c to class of xs |
|||
if list is c then |
|||
if 0 < n then |
|||
items 1 thru min(n, length of xs) of xs |
|||
else |
|||
{} |
|||
end if |
|||
else if string is c then |
|||
if 0 < n then |
|||
text 1 thru min(n, length of xs) of xs |
|||
else |
|||
"" |
|||
end if |
|||
else if script is c then |
|||
set ys to {} |
|||
repeat with i from 1 to n |
|||
set end of ys to xs's |λ|() |
|||
end repeat |
|||
return ys |
|||
else |
|||
missing value |
|||
end if |
|||
end take |
|||
-- toLower :: String -> String |
-- toLower :: String -> String |