Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erlang: Sorting arrays

Tags:

erlang

I am new with functional programming languages and I can't understand why in Erlang, if I take a BubbleSort, QuickSort or any other sorting algorithms and try to sort [8] it will return "\b". Or [12,10,11] will return "\n\v\f". Can someone please help me?

like image 982
Lívia Amaral Avatar asked Aug 07 '26 12:08

Lívia Amaral


2 Answers

It's because they mean the same thing: 8 in ASCII is "\b". See the "lists!" section here.

Erlang will print lists of numbers as numbers only when at least one of them could not also represent a letter!

So the erlang shell is trying to help you out by making its best guess about what you want to see. Occasionally, you get a string when you meant to see a list of integers which can be confusing. The following illustrates this point:

1> [104, 101, 108, 108, 111].
"hello"
2> [104, 101, 108, 108, 111, -1].
[104,101,108,108,111,-1]
3> [104, 101, 108, 108, 111] =:= "hello".
true
like image 176
David Weldon Avatar answered Aug 09 '26 12:08

David Weldon


This is due to the fact that Erlang represents strings as lists of numbers. When printing such a list, the Erlang output function will look to see whether your list contains all numbers that correspond to ASCII character values. If so, then it prints your list as a string.

It sounds like your code is working correctly. Try sorting [12345, 29348, 978] with your existing code to see what happens.

See the reference manual section 2.11 String for information about this.

like image 31
Greg Hewgill Avatar answered Aug 09 '26 11:08

Greg Hewgill



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!