问题
How can I delete the element elem
in list L
? If the list does not contain elem, then the function should return the list unchanged.
For instance:
L = [1, 3, 4, 0, 5, 7]
elem = 5
So far I have the following function:
fun removeElem elem myList[] = myList
| removeElem (myList::tl) = if mem myList elem then
rm elem myList[]
else
removeElem elem tl
回答1:
You can turn the question around and ask how to keep only those items not equal to elem
. This fits cleanly with filter
:
fun removeElem elem myList = filter (fn x => x <> elem) myList
回答2:
This code will accomplish what you want to do: remove the element (actually it will remove all instances of the element if there are more than one) and return the rest of the list as-is:
fun remove_element (list, element) =
case list of
[] => []
| list_head::list_tail => let val a = remove_element(list_tail, element)
in
if list_head = element
then a
else list_head::a
end
回答3:
fun delete (s,[]) = []
| delete (s,x::xs') =
if s = x then xs' (* more efficient than call delete function again *)
else x::delete(s, xs')
回答4:
fun remove_element (elemlist, elem) =
case elemlist of
[] => []
| head::tail => if elem = head
then remove_element (tail, elem)
else head::remove_element (tail, elem)
Output SML/NJ:
val remove_element = fn : ''a list * ''a -> ''a list
val it = () : unit
(* matching *)
- remove_element ([1,2,3,4,5], 4);
val it = [1,2,3,5] : int list
(* non matching *)
- remove_element ([1,2,3,4,5], 7);
val it = [1,2,3,4,5] : int list
(* multiple instances *)
- remove_element ([1,3,4,4,5],4);
val it = [1,3,5] : int list
回答5:
With no libraries or extra functions
fun remv(L, c) =
if null(L) then nil
else if c=hd(L) then remv(tl(L), c)
else hd(L)::remv(tl(L), c);
回答6:
You can try this code.
fun remove_element (elemlist:int list, elem:int) =
case elemlist of
[] => []
| head::tail => if elem = head
then remove_element (tail, elem)
else head::remove_element (tail, elem)
回答7:
also you can use this function to remove duplicate entries from a list:
fun remove_duplicates(xs: ''a list) =
let
fun helper(ds: ''a list, m: ''a) =
if null ds
then []
else if hd ds = m
then helper(tl ds, m)
else hd ds :: helper(tl ds, m)
in
if null xs
then []
else hd xs :: remove_duplicates( helper(tl xs, hd xs) )
end
来源:https://stackoverflow.com/questions/8558700/sml-remove-the-entry-from-the-list