Remove duplicate elements: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
Hout (talk | contribs)
Undo revision 223069 by Hout (talk)
Line 98:
 
=={{header|AppleScript}}==
<lang applescript>--unique({1, nub2, ::3, ["a]", ->"b", [a]"c", 2, 3, 4, "b", "c", "d"})
 
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)
script mf
-- 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
end script
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(mf'smy notEq, {x:x, fnEq:fnEq}), xs))
else
xxs
end if
end nubBy
-- 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
end script