[Prev] Best programming language (how to Stop worrying, fall in love with code)

Source: Internet
Author: User
Tags rand


Original: The best programming Language (or what to Stop worrying and love the Code) by A. Castro-castilla

Every once in a while, someone will think it's time to write another post about what programming language is best, what powerful features an ancient language has, or which new language is right. Now, it's my turn to write. I can finally talk about my view of the programming language.

First of all, disclaimer: Unless you have used more than 30 languages, and have been tortured by the code of all these languages (or most) written by others, you are not objective. So yes, I have a bias, just like most people who talk about this topic. In fact, I believe that once you are proficient in multiple languages, the topic becomes absurd.
To someone who is too lazy to read: The Great language
I hereby announce the following languages as great languages within the scope of this blog.
    • Assembly: The language of the machine.
    • C: The language of the system development.
    • Javascript: The language of the network.
    • Scheme: A lightweight, embeddable, and extremely flexible language that can be compiled into C and JavaScript.
Most of the code examples come from Rosetta.
Applicable languages I call these languages the appropriate language, not because they are the best. They are only the most commonly used language in the world and are therefore suitable for productive software. You can, of course, skip the controversy and make a decision intuitively. If so, take a look at the next section.
Ada

I have always been interested in the concept of design software around storage security. This is a viable concept for real-time operating systems and applications in a variety of critical systems. If you are thinking about using this language, you are likely to have a fairly professional background and do not need to read this post. This language is the language after becoming a master, and there is not much choice at that time. Some ADA codes:

   function Best_shuffle (s:string) return String is      t:string (S ' Range): = S;      Tmp:character;   Begin for      I in S ' Range loop for         J in S ' Range loop            if I/= J and S (i)/= T (j) and S (j)/= T (i) then               tmp
   
    := T (I);               T (I): = t (J);               T (J): = TMP;            End If;         End Loop;      End Loop;      return T;   End Best_shuffle;
   

It's safe to look at, right? :)


Bourne (Again) shell I often think: do I really need to write this Linux script in the shell language? Is that really necessary? It's okay to write scripts without a shell, because sooner or later you have to deal with this script face-to-head, and then wonder how it was written in the age of bare metal without stackoverflow.com. In short, with the right book guide, you'll find that the language just needs a little retouching (and consistency). There is no such thing as a great place to broaden your horizons, improve efficiency, or have a business perspective that is just a world of Unix and Unix-like. However, it is indispensable in system management and does not look so bad. It's a bit like JavaScript and needs to know more about the practical specs than any other language.
What do I do with the Unix shell?
    • Osx/linux/posix System Management
    • Task automation
    • Unlocking the power of the command line
Here's a little bit of Bourne shell code. Enjoy these Boolean expressions!

#!/usr/bin/env shl= "1" while ["$l"-le 5]  does  m= "1" while  ["$m"-le "$l"]    do    printf "*"    m= ' expr "$m" + 1 '  done  echo  l= ' expr "$l" + 1 ' done

C Even if you don't like C, you have to respect it. It can be said to be one of the greatest languages. It can really write machine-level code (not its model). It is the father of Unix, the originator of all Class C languages, and the lingua-generic language of the system development community. It is a veteran, experienced time test, widely disseminated. Too many development, commissioning, and performance analysis tools support the development of C, which also reduces it as a language defect (in my opinion, not many defects). This is a language that really achieves its goal: Universal assembly language for all processors. Today, it can even be the most bizarre of the architecture in the actual assembly language, compared to the C compiler generated code, it is difficult to write better code.
So, C is a powerful tool, but it's not easy to master it. This language is callous and you have to know exactly what you are doing. Because of this, C language is to teach people to understand the language of the machine. There's something wonderful about it, and there's a practical side to it: if you don't have the underlying functionality provided by C, some things can't be done. C language programmers must thoroughly understand what they are doing, and in the long run, this allows them to produce highly reliable software. If there is a language that can affect the divine status of C, it must be a very good low-level language to support concurrency, or a god-like language with performance such as Haskell, which is popular as a C language.
Some C language codes in the Linux kernel

int Next_pidmap (struct pid_namespace *pid_ns, unsigned int last) {    int offset;    struct Pidmap *map, *end;    if (last >= pid_max_limit)        return-1;    Offset = (last + 1) & Bits_per_page_mask;   Map = &pid_ns->pidmap[(last + 1)/bits_per_page];   End = &pid_ns->pidmap[PIDMAP_ENTRIES];   for (; map < end; map++, offset = 0) {       if (unlikely (!map->page))           continue;       offset = find_next_bit ((map)->page, bits_per_page, offset);       if (offset < bits_per_page)           return mk_pid (Pid_ns, map, offset);   }   return-1;}


C++

Monster. It was the first language I contacted, and it was not until I tried many other languages that I realized how badly it affected my efficiency and limited my technology. I fully agree with some well-known programmers who have a very low evaluation of C + +. C + +, like Bjarne Stoustrup, adds all the functions he can think of to the results of C. Mastering C + + consumes a lot of energy, which can reduce programming efficiency by more than 80%. Think of it this way: your brain capacity is X, capacity is limited, no matter how much you have, you should make room for important things as much as possible. It is wise to use less brainpower on the language itself, mostly to solve problems and write algorithms. If the language is complex, no matter how smart you are, you need to spend more of your brainpower on grammar and semantics, rather than focusing on implementing your ideas in code.
I think C + + is a typical example of high difficulty and low yield. I agree that it is difficult to write large programs in C (but it is still possible to look at the Linux kernel). The Go,rust and D languages are better in every way, but the fact is that C + + is widely used all over the world.
Here is an example of a good C + + code that uses a template. User code snippets like this in C + + code understood more than the definition of a template or class.

#include <fstream> #include <string> #include <iostream>int main (int argc, char** argv) {    int Linec Ount = 0;    Std::string line;    Std::ifstream infile (argv[1]);    if (infile)    {        while (getline (infile, line))        {            std::cout << linecount << ":" << Lin e << ' \ n ';            linecount++;        }    }    Infile.close ();    return 0;}

Then there is the template code, which is simple (but it will naturally get messy).

Namespace rosettacode{Template<typename t> class Queue {public:queue ();    ~queue ();    void push (t const& t);    T pop ();  bool Empty ();    Private:void drop ();    struct node;    node* Head;  node* tail;  };    Template<typename t> struct Queue<t>::node {T data;    Node* Next;  Node (t const& t): Data (t), next (0) {}}; Template<typename t> Queue<t>::queue (): Head (0) {} template<typename t> inline void queue<    T&gt::d rop () {node* n = head;    Head = head->next;  Delete N;  } template<typename t> Queue<t>::~queue () {while (!empty ()) drop (); } template<typename t> void queue<t>::p ush (t const& t) {node*& next = head? tail->next:he    Ad    Next = new node (t);  tail = next;    } template<typename t> T Queue<t>::p op () {T tmp = head->data;    Drop ();  return TMP; } template<typename t> bool Queue<t>::empty () {return head = = 0; }}


C # Enterprise Language, which focuses on reducing programmer creativity in order to achieve the substitution in large organizations. Object-oriented, static classes, redundant, lots of libraries and boilerplate templates, all of which imply the lineage of Microsoft. Don't get me wrong, this language is not bad. It's just not tempting, and that's exactly what Microsoft is aiming for. At the very least, it has made considerable progress compared to Visual Basic. I use it in the following situations:
    • Under Windows development
    • Game development (well, mainly due to Microsoft, I still prefer old buddy C or C + +)
    • There are sensational things in this language: Unity3d, Xamarin,. NET, XNA.
code example

Using system;using system.collections.generic;using system.io;using system.linq;class Program{    Static Sorteddictionary<titem, int> getfrequencies<titem> (ienumerable<titem> items)    {        var Dictionary = new Sorteddictionary<titem, int> ();        foreach (var item in items)        {            if (dictionary. ContainsKey (item))            {                dictionary[item]++;            }            else            {                Dictionary[item] = 1;            }        }        return dictionary;    }    static void Main (string[] arguments)    {        var file = arguments. FirstOrDefault ();        if (file.exists (file))        {            var text = file.readalltext (file);            foreach (var entry in getfrequencies (text))            {                Console.WriteLine ("{0}: {1}", entry. Key, entry. Value);}}}    
Does it look like Java?


Objective-c I have a much better impression of objective-c than C + + (and C #). Its syntax is not beautiful, but as a language I like it. It has a good nextstep-based library, which is a true sublimation of C, and does not extend out of control, making the keyword ambiguous with its parent language. As I said, its code is not very beautiful and not easy to read, especially when nesting functions, but its beauty lies in concepts and methods, not syntax. Look at this nested call:
Char bytes[] = "some data"; NSString *string = [[NSString alloc] initwithbytes:bytes length:9 encoding:nsasciistringencoding];


For the descendants of C, this is a wonderful piece of code that uses the so-called block of code in OBJECTIVE-C.

#import <foundation/foundation.h>typedef Nsarray * (^SOFN) (ID); SOFN s_of_n_creator (int n) {  Nsmutablearray *sample = [[Nsmutablearray alloc] initwithcapacity:n];  __block int i = 0;  return ^ (ID item) {    i++;    if (i <= N) {      [sample Addobject:item];    } else if (rand ()% i < n) {      sample[rand ()% n] = Item;    }    return sample;  };} int main (int argc, const char *argv[]) {  @autoreleasepool {    Nscountedset *bin = [[Nscountedset alloc] Init];
   for (int trial = 0; trial < 100000; trial++) {      sofn s_of_n = S_of_n_creator (3);      Nsarray *sample;      for (int i = 0; i < i++) {        sample = S_of_n (@ (i));      }      [Bin Addobjectsfromarray:sample];    }    NSLog (@ "%@", bin);  }  return 0;}

Clojure as a scheme programmer, I pay tribute to Clojure: This is what people call Modern Lisp, with unique characteristics. I think Clojure's strengths are interoperability with Java and concurrency in the core language. It is like a sibling to Scala, but each has its own characteristics: one is Lisp, the other is a mixture of object-oriented and functional languages, and Clojure is less popular because of too many brackets. Choosing which of these two languages to program depends on your personal style, because neither of them provides support for long-term and successful application output, which is less than the same JVM-based Java and PHP. For any JVM-based language, another thing to consider is the startup time of the virtual machines, which are slightly cumbersome to handle small tasks. I will use Clojure in the following situations:
    • Network programming. There are many good options for network programming, and the Clojure group looks very active in this area.
    • When you want to bypass the Java set to use the JVM. This will make the programmer both happy and efficient.
    • Exploratory programming, developed into product code exploration. This is actually a lisp's strength, but Clojure is based on Java and has many sources of open source code.
    • Android app development? The graphical user excuse pattern developed by the Android program is largely based on class inheritance (which means you can use it as a plug-in library and must follow certain constructs). This can be done, but it is not as natural as inheriting directly from Java.
The classic Clojure code:

(defn divides?) [k N] (= (rem n k) 0)) (Defn prime?) [N]  (If (< n 2)    false    (empty?) (Filter # (divides% n) (Take-while # (<= (*%) n) (range 2 N)))))

A Lisp-type simple queue definition,

(Defn make-queue []  (Atom [])) (Defn enqueue [Q x]  (swap! q Conj x)) (Defn dequeue [Q]  (if (Seq @q)    (Let [x (first @q)]      (swap! q Subvec 1)      x)    (throw (illegalstateexception). "Can ' t pops an empty queue."))) (Defn queue-empty?) [Q]  (empty? @q))

D I used to like D,d like a perfect version of C + +. D1 like Python for the underlying, such as Python and C. It's great: you can feel how quickly you're developing it, focusing on algorithms rather than languages, but not sacrificing the underlying controls for a rainy future. D2 with a lot of C + + complexity, but also with Andrei Alexandrescu innovation means. Some people are not satisfied with this, although D2 more attention to concurrency. D2 is no longer a concise language, but because there are many features that are not tested, it feels more like an experimental language. I still like it, but I think its function pales in the face of the high usage rate of C + + (once complicated). In addition, I think go is annexing the market d should have. Even if D was done faster and more cool, Walter and Andrei couldn't compete with Google. You might like D as much as I do, but it's not a bright future. or continue using C + +, or try go, which is more powerful with local concurrency support. So, when will I use D language?
    • Develop a project from scratch that has an interface with C, or that is associated with a. C + +. However, you have to envision the interface in advance. For example, if you need to use a C + + GUI library, I don't recommend using D. Since this usually means that the inheritance of C + + is handled internally, all the benefits will be offset. If you need a C + + plug-in library, do it: Create objects, use their functions, but not templates or C + + inheritance.
    • When you are doing the underlying programming and need fast binary functionality. Still, doing your own thing is like a standalone program.
    • You want the language to be better at supporting concurrency locally.
Let's take a look at some of the idiomatic methods of D2 with pure functions and immutable declarations.
UINT Grayencode (in uint N) Pure nothrow {    return n ^ (n >> 1);} UINT Graydecode (UINT N) pure nothrow {    Auto p = n;    while (n >>= 1)        p ^= N;    return p;} void Main () {    import Std.stdio;    N     N2      enc     dec2 Dec ". Writeln;    foreach (immutable n; 0.) {        immutable g = N.grayencode;        Immutable d = g.graydecode;        WRITEFLN ("%2d:%5b =%5b =%5b:%2d", N, N, G, D, D);        assert (d = = n);}    }
The largest element of the table:

[9, 4, 3, 8, 5].reduce!max.writeln;
It is definitely more concise than C + +, more expressive, the gap is not a little bit.


Erlang This is a clear-end language. The webpage of Erlang speaks clearly: (...). Build a soft real-time system with strong scalability and high availability. Customers throughout the telecommunications, banking, e-commerce, computer telephony and instant messaging and other industries. The runtime system of Erlang is inherently support for concurrency, distribution, and fault tolerance. Erlang has proven reliable and has produced some highly difficult applications, such as WhatsApp.
The code itself gives a sense of power, and its syntax is simple and easy to read.
Look at a simple concurrent program code:
-module (HW).-export ([start/0]). Start (),   [Spawn (Fun ()  , Say (self (), X) end) | | X <-[' Enjoy ', ' Rosetta ', ' Code '],   wait (2),   Ok.say (pid,str)-   io:fwrite ("~s~n", [Str]),   Pid! Done.wait (n), receive done, case       N of           0, 0;           _n, Wait (N-1)       end   end.

Go I haven't personally used it yet. But it is clear that Google's attempt to create a language based on C, with C + + advantages, and concurrent support is stronger than both. It has better functionality than C + + and is much simpler. It has no unsafe pointer operations, has closures, first-level functions, and garbage collection mechanisms. Go may be the future of server language. So, when do I try go?
    • Write server applications that require very high performance and reliability, including network applications.
    • Write high concurrency code that requires the underlying control (or I prefer Erlang).
Concurrency code for Go
Package Mainimport (    "FMT"    "Math/rand" "Time    ") func main () {    words: = []string{"Enjoy", "Rosetta", " Code "}    Rand. Seed (time. Now (). Unixnano ())    Q: = Make (Chan string)    for _, W: = Range words {        go func (W string) {Time            . Sleep (time. Duration (Rand. Int63n (1E9)))            Q <-w        } (w)    } for    I: = 0; i < len (words); i++ {        fmt. Println (<-Q)    }}

Haskell is like a more advanced thinking tool than any other language on this list. It has a series of omnipotent libraries and a group of loyal supporters. It can be said that this is a high-threshold language. I think using it can open up ideas and get you in touch with the smartest people in the programming world.
Even if it wasn't for the real program, I think Haskell is worth learning. Although it is a relatively vague language, I am positioning it as "applicable" because it is useful in some ways and the financial sector is the first to take the brunt.
Haskell's code is often very compact and expressive, albeit somewhat abstract (since many functions are conceptually manipulated rather than a step in the process). I personally don't like its syntax (I think it's too much), but at least it serves a purpose, not confusing (say you perl! )。 This language is beautiful and coherent, see for yourself:

BinarySearch:: Integral a = (A, a), maybe Abinarysearch p (low,high)  | High < lo w = Nothing  | otherwise = to      -mid = (low + high) ' div ' 2      in case p mid        of LT-and BinarySearch p (Low, MI d-1)        GT, BinarySearch p (mid+1, High)        EQ-Just mid

Next post will be released tomorrow, please look forward to

This article is translated by the original author's permission, without permission to reprint

[Prev] Best programming language (how to Stop worrying, fall in love with code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.