0
votes

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.

3

3 Answers

1
votes

1) just call the function one step earlier

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

2) you could do this:

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

in other cases you could use a switch case

0
votes

You don't need to compare the first letter of the strings, because you can just use relational operators on strings:

1> "a" < "b".
true
2> "b" < "a".
false

However, if you do want to compare the first letter of a string, remember that a string is just a list, so you can use the cons operator to do pattern matching as with any list:

get_first_letter([[FirstLetter|FirstString]|Rest]) -> FirstLetter.

1> whatever:get_first_letter(["Hello", "There"]).
72

72 being the ASCII value of 'H' (if other character sets are supported, this might have a different value). You can now use FirstLetter in a guard, e.g.

get_first_letter([[FirstLetter|FirstString]|Rest]) when FirstLetter == $H -> FirstLetter.

Now get_first_letter will only match if the first letter of the first string is H. Note that the above example assumes a single list of strings; you can easily extrapolate for a function that accepts two lists of strings.