Search code examples
stringfunctionerlangcomparemergesort

erlang function calls after when to compare strings


Trying to sort a list of strings with mergesort. my problem is that i don't know how to compare the first letter of the strings.

my idea was this but this leads to two problems:

merge([],X) -> X;
merge(X,[]) -> X;
merge([X|XS],[Y|YS]) when check_swap(X,Y)-> [X] ++ merge(XS,[Y|YS]);
merge([X|XS],[Y|YS]) -> [Y] ++ merge([X|XS], YS).

sort([]) -> [];
sort([A|[]])-> [A];
sort (L) -> Len=length(L) div 2,
merge(sort(lists:sublist(L, Len)),sort(lists:nthtail(Len, L))).

%check if strings should be swaped or not
change_strings(StingA,StringB) when lists:nth(1,StingA)<lists:nth(1,StringB)->true;
....
  1. Problem is that i can't call a function after when,case or if. What is the better way to do this?

    ./textSort.erl:28: call to local/imported function check_swap/2 is illegal in guard

  2. Problem: How can i combine various conditions with AND and OR. When do i use ", ; or and orelse andalso" and how can i combine them like in other languages with a() order? is there are better way to do

    change_strings(X,Y) when (A < B,B==3) ; (A < B,B==4) -> true;

May its an easy failure. getting just started in erlang.


Solution

  • 1) just call the function one step earlier

    X1 = change_strings(X),
    if
        X1 == true ->
            doSomething();
        true ->
            doSomethingElse()
    end