Haskell
(just knocking a few characters off Mark Rushakoff's effort, I'd rather it was posted as a comment on his)
h y=[x|x<-y,[_]<-[filter(==x)y]]
which is better Haskell idiom but maybe harder to follow for non-Haskellers than this:
h y=[z|x<-y,[z]<-[filter(==x)y]]
Edit to add an explanation for hiena and others:
I'll assume you understand Mark's version, so I'll just cover the change. Mark's expression:
(<2).length $ filter (==x) y
filters y
to get the list of elements that == x
, finds the length of that list and makes sure it's less than two. (in fact it must be length one, but ==1
is longer than <2
) My version:
[z] <- [filter(==x)y]
does the same filter, then puts the resulting list into a list as the only element. Now the arrow (meant to look like set inclusion!) says "for every element of the RHS list in turn, call that element [z]
". [z]
is the list containing the single element z
, so the element "filter(==x)y
" can only be called "[z]
" if it contains exactly one element. Otherwise it gets discarded and is never used as a value of z
. So the z
's (which are returned on the left of the |
in the list comprehension) are exactly the x
's that make the filter
return a list of length one.
That was my second version, my first version returns x
instead of z
- because they're the same anyway - and renames z
to _
which is the Haskell symbol for "this value isn't going to be used so I'm not going to complicate my code by giving it a name".