Remove duplicate elements: Difference between revisions
Content deleted Content added
Line 98:
=={{header|AppleScript}}==
<lang applescript>
on unique(x)
set R to {}
repeat with i in x
if i is not in R then set end of R to i's contents
end repeat
return R
end unique</lang>
Or, more generally, we can allow for customised definitions of equality and duplication, by following the Haskell prelude in defining a '''nub :: [a] -> [a]''' function which is a special case of '''nubBy :: (a -> a -> Bool) -> [a] -> [a]'''
In the following example, equality is defined as case-insensitive for strings. We would obtain a different list of unique strings by adjusting the '''Eq :: a -> a -> Bool''' function to make it consider case.
{{trans|JavaScript}}
{{trans|Haskell}}
<lang AppleScript>-- nub :: [a] -> [a]
on nub(xs)
script mf
Line 112 ⟶ 131:
-- nubBy :: (a -> a -> Bool) -> [a] -> [a]
on nubBy(fnEq, xxs)
-- notEq :: a -> Bool▼
on notEq(a)▼
set mf to mReturn(my closure's fnEq)▼
not (mf's lambda(a, my closure's x))▼
end notEq▼
set lng to length of xxs
if lng > 1 then
Line 126 ⟶ 136:
set xs to items 2 thru -1 of xxs
{x} & nubBy(fnEq, filter(mClosure(
else
xxs
end if
end nubBy
end script
|