2014-01-12 7 views
3

방금 ​​SML에서 함수 프로그래밍을 배우기 시작했으며 다음 두 함수를 어떻게 단일 함수로 결합 할 수 있는지 알고 싶습니다. 분리 함수는 도우미 함수 'removed'를 사용하여 모든 유형 ('a) 목록의 중복을 삭제합니다.SML의 목록에서 중복 항목 제거

fun isolate [] = [] 
    | isolate (l as x::xs) = x::isolate(remove(x,xs)) 

fun remove (x,[]) = [] 
    | remove (x,l as y::ys) = if x = y then remove(x,ys) else y::remove(x,ys) 

그래서 SML의 구조를 더 잘 이해하기 위해 분리 내에서 함수 제거를 어떻게 포함할까요? 이것은 사소한 것처럼 보일지 모르지만 나는 그것에 대해 생각하고 그것을 파악할 수 없습니다. 도와 줘서 고마워!

답변

7

한 가지 방법은 을 isolate 안에 정의하는 것입니다. 진짜로이 모든 remove가하는 것과 같은 일을하는 라이브러리 함수 List.filter를 사용 비록

fun isolate [] = [] 
    | isolate (l as x::xs) = 
     let fun remove (x,[]) = [] 
      | remove (x,l as y::ys) = if x = y 
             then remove(x,ys) 
             else y::remove(x,ys) 
     in 
     x::isolate(remove(x,xs)) 
     end 

다른 방법으로는, 중복 제거를 하나 개의 기능을 확인합니다.

fun isolate [] = [] 
    | isolate (x::xs) = x::isolate(List.filter (fn y => y <> x) xs) 
+0

이 정확히 내가 무엇을 찾고 있었다! 고맙습니다! – macalaca

+0

안녕하세요 @ qaphla, 코드를 컴파일 할 때 연산자와 피연산자가 일치하지 않는 오류가 발생했습니다. 오류를 찾을 수 없습니다. – macalaca

+0

신경 쓰지 마세요. let의 'in'부분에서 remove 메소드를 호출하면 찾았습니다. 당신은 올바른 주장을 전달하지 않습니다. – macalaca

0

나는이 문제의 다음과 같은 솔루션을 제출하다 싶어 :

fun remove_duplicates(xs: int list) = 
    let 
     fun check(xs: int list, item: int) = 
      if null xs 
      then false 
      else if hd xs = item 
      then true 
      else check (tl xs, item) 
     fun go_through_list(xs: int list) = 
      if null xs 
      then [] 
      else if check(tl xs, hd xs) 
       then go_through_list(tl xs) 
       else hd xs :: go_through_list(tl xs) 
    in 
     go_through_list(xs) 
    end 

그것은 @qaphla

0

내 생각으로 제의 솔루션보다 더 많은 코드 라인이다 :에 중첩 된 함수를 정의 목록에 중복 된 요소가 있는지 확인하십시오.

fun set(nums:int list)= 
    let fun duplicate(x:int, l:int list)= 
    if null l 
    then false 
    else hd l=x orelse duplicate(x,tl l) 
    in 
     if null nums 
     then [] 
     else 
     let val s=set(tl nums) 
     in if duplicate(hd nums,s) 
     then s 
     else hd nums::s 
     end 
    end 

그러나 목록에 중복 요소가 있는지 확인하십시오. 모자는 복제 된 모든 요소에 대해 마지막으로 남아 있습니다.

0

내 생각이 먼저 목록을 정렬하는 것입니다, 다음 반복적으로 중복없이 새로운 목록을 반환 :

fun remove_duplicates(l: int list) = 
if null(l) 
then [] 
else if null(tl l) 
then l 
else 
    let 
     fun compare(x: int, y: int) = x > y 
     fun sort(l: int list) = ListMergeSort.sort(compare) l 
     val l_sorted = sort(l) 
    in 
     if (hd l_sorted) = (hd (tl l_sorted)) 
     then remove_duplicates(tl l_sorted) 
     else (hd l_sorted)::remove_duplicates(tl l_sorted) 
    end