Welcome to W3Courses
 Like Us on Facebook

Programming

List Member Function using Prolog Source Code

The following code checks if an element is a member of a given list

CODE
member(X, [X|Y]).
member(X, [H|L]) :- member(X, L).


RESULT
?- member(b, [a,b,c]).
Yes

Share

List Merge Function using Prolog Source Code

The following code merges two list in ascending order.

 merge([],Ys,Ys).
 merge(Xs,[],Xs).
 merge([X|Xs],[Y|Ys],[X|R]):- X<Y,merge(Xs,[Y|Ys],R).
 merge([X|Xs],[Y|Ys],[Y|R]):-X>Y,merge([X|Xs],Ys,R).
 merge([X|Xs],[X|Ys],[X,X|R]):-merge(Xs,Ys,R).

Share

MergeSort Function using Prolog Source Code

The following code merges and sorts two lists

mergesort([],[]).
mergesort([X],[X]).
mergesort([X,Y|Xs],Ys) :- split([X,Y|Xs],Xs1,Xs2), mergesort(Xs1,Ys1), mergesort(Xs2,Ys2), merge(Ys1,Ys2,Ys).

split([],[],[]).
split([X|Xs],[X|Ys],Zs) :- split(Xs,Zs,Ys).

merge([],Xs,Xs).
merge(Xs,[],Xs).
merge([X|Xs],[Y|Ys],[Z|Zs]) :- ( X =< Y -> Z = X, merge(Xs,[Y|Ys],Zs) ; Z = Y, merge([X|Xs],Ys,Zs)).

Share

Powersort Function using Prolog Source Code

The following code sorts lists

subset([],[]).
subset(S, [|T]) :- subset(S,T).
subset([H|S],[H|T]) :- subset(S,T).
powerset(Set,PowerSet) :- bagof(S,subset(S,Set),Powerset).
num(X,[X|T],T).
num(X,[H|T],[H|B]) :- num(X,T,B).
subset([],_).
subset([H|T],A) :- num(H,A,B), subset(T,B).
powerset(Set,Powerset) :- setoff(S, subset(S,Set), Powerset).

Share

QuickSort Function using Prolog Source Code

Quick Sort code:

gtq(X,Y) :- X @> Y.  

quicksort( [],[] ).

quicksort( [X | Tail], Sorted) :-
        split( X, Tail, Small, Big),
        quicksort( Small, SortedSmall),
        quicksort( Big, SortedBig),
        conc( SortedSmall, [X | SortedBig], Sorted).

split( _, [], [], []).

Share

Replace Function using Prolog Source Code

The following code replaces an element with a new element in the list

 CODE
 replace([],A,B,[]).
 replace([H|T],A,B,[B|Result]) :- H=A, replace(T,A,B,Result).
 replace([H|T],A,B,[H|Result]) :- replace(T,A,B,Result).


 RESULT
 ?- replace([a,b,a,c,a,d],a,w,R).
 R = [w, b, w, c, w, d]
 Yes

Share

Append Two Lists Using Scheme Source Code

The following code appends two lists

 (define (append x y)
         (cond((null? x) y)
                (else (cons (car x) (append (cdr x) y) ))))

Share

Cartesian Product Using Scheme Source Code

Cartesian product code

Share

Copy List Using Scheme Source Code

The following code copies a list

 (define (copy x)
       (cond((null? x) ‘())
               (else (cons (car x) (copy(cdr x)) ))))

Share

Cube Function Using Scheme Source Code

The following code finds the cube of a number

 (define cube(lambda(x) (* x (* x x))))

or

 (define cube(lambda(x) (* x x x)))

 

Share