Showing posts with label DLanguage. Show all posts
Showing posts with label DLanguage. Show all posts

Saturday, October 1, 2016

min_fgrep: minimal fgrep command in D

By Vasudev Ram

min_fgrep pattern < file

The Unix fgrep command finds fixed-string patterns (i.e. not regular expression patterns) in its input and prints the lines containing them. It is part of the grep family of Unix commands, which also includes grep itself, and egrep.

All three of grep, fgrep and egrep originally had slightly different behaviors (with respect to number and types of patterns supported), although, according to the Open Group link in the previous paragraph, fgrep is marked as LEGACY. I'm guessing that means the functionality of fgrep is now included in grep, via some command-line option, and maybe the same for egrep too.

Here is a minimal fgrep-like program written in D. It does not support reading from a filename given as a command-line argument, in this initial version; it only supports reading from stdin (standard input), which means you have to either redirect its standard input to come from a file, or pipe the output of another command to it.
/*
File: min_fgrep.d
Purpose: A minimal fgrep-like command in D.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
*/

import std.stdio;
import std.algorithm.searching;

void usage(string[] args) {
    stderr.writeln("Usage: ", args[0], " pattern");
    stderr.writeln("Prints lines from standard input that contain pattern.");
}

int main(string[] args) {
    if (args.length != 2) {
        stderr.writeln("No pattern given.");
        usage(args);
        return 1;
    }

    string pattern = args[1];
    try {
        foreach(line; stdin.byLine)
        {
            if (canFind(line, pattern)) {
                writeln(line);
            }
        }
    } catch (Exception e) {
        stderr.writeln("Caught an Exception. ", e.msg);
    }
    return 0;
}
Compile with:
$ dmd min_fgrep.d
I ran it with its standard input redirected to come from its own source file:
$ min_fgrep < min_fgrep.d string
and got the output:
void usage(string[] args) {
int main(string[] args) {
    string pattern = args[1];
(Bold style added by me in the post, not part of the min_fgrep output, unlike with some greps.)

Running it as part of a pipeline:

$ type min_fgrep.d | min_fgrep string > c
gave the same output. The interesting thing here is not the min_fgrep program itself - that is very simple, as can be seen from the code. What is interesting is that the canFind function is not specific to type string; instead it is from the std.algorithm.searching module of the D standard library (Phobos), and it is generalized - i.e. it works on D ranges, which are a rather cool and powerful feature of D. This is done using D's template metaprogramming / generic programming features. And since the version of the function specialized to the string type is generated at compile time, there is no run-time overhead due to genericity (I need to verify the exact details, but I think that is what happens).

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

FlyWheel - Managed WordPress Hosting


Thursday, September 22, 2016

num_cores: find number of cores in your PC's processor

By Vasudev Ram

Here is a simple D language utility, num_cores.d, which, when compiled (once) and run (any number of times), will show you the number of cores in the processor in your PC:
// num_cores.d
// A utility to show the number of cores in the processor in your PC.

import std.stdio;
import std.parallelism;

int num_cores() {
    return totalCPUs;
}

void main() {
    writeln("This computer's processor has ", num_cores, " core(s).");
}
The program uses the function totalCPUs from the D standard library module std.parallelism to get the number of cores.

To use it, download and install a D compiler such as DMD, the Digital Mars D compiler (or LDC or GDC). Use of DMD is shown here.

Then compile the program with:
dmd num_cores.d
Then run it:
num_cores
Output:
This computer's processor has 4 core(s).

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes



Tuesday, September 20, 2016

Calling a simple C function from D - strcmp

By Vasudev Ram


D => C

It's quite useful to be able to communicate between modules of code written in different languages, or, in other words, to be able to call code in one language from code in another language. Some of the reasons why it is useful, are:

- some functions that you need may already be written in different languages, so it may be quicker to be able to call cross-language from function f1 in language L1 to function f2 in language L2, than to write both f1 and f2 in L1 (or in L2) from scratch;

- the function f2 that you need may not be as easy to write in language L1 as it is in language L2 (or you don't have people who can do it in L1 right now);

- f2 may run faster when written in L2 than in L1;

- etc.

I was looking into how to call C code from D code. One source of information is this page on the D site (from the section on the language spec):

Interfacing to C

Here is an example of calling a simple C function, strcmp from the standard C library, from a D program, adapted from information on that page:
/*
File: call_strcmp.d
Purpose: Show how to call a simple C string function like strcmp from D.
Author: Vasudev Ram
Copyright 2016 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: http://jugad2.blogspot.com
*/

extern (C) int strcmp(const char* s, const char* t);

import std.stdio;
import std.string;

int use_strcmp(char[] s)
{
    // Use toStringz to convert s to a C-style NULL-terminated string.
    return strcmp(std.string.toStringz(s), "mango");
}

void main(string[] args)
{
    foreach(s; ["apple", "mango", "pear"])
    {
        // Use dup to convert the immutable string s to a char[] so
        // it can be passed to use_strcmp.
        writeln("Compare \"", s.dup, "\" to \"mango\": ", use_strcmp(s.dup));
    }
}
I compiled it with DMD (the Digital Mars D compiler):
$ dmd call_strcmp.d
and ran it:
$ call_strcmp
Compare "apple" to "mango": -1
Compare "mango" to "mango": 0
Compare "pear" to "mango": 1
The output shows that the C function strcmp does get called from the D program, and gives the right results, -1, 0, and 1, for the cases where the first argument was less than, equal to, or greater than the second argument (in sort order), respectively.

Of course, not all kinds of calls from D to C are going to be as easy as this (see the Interfacing reference linked above), but its nice that the easy things are easy (as the Perl folks say :).

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes



Thursday, September 15, 2016

Component programming in D - DDJ article by Walter Bright

By Vasudev Ram

After this post of yesterday:

Func-y D + Python pipeline to generate PDF

I was doing a search today for some D language topics, and came across this article in Dr. Dobb's Journal (DDJ) by Walter Bright, the creator of D:

Component programming in D

It's just 4 pages long, and is a good article. It talks about the motivations, principles, and techniques of component creation in D (using templates / generics, ranges, and functional programming features) and has the code for a small reusable component. He takes the reader through the process of building it up step by step.

Recommended.

- Vasudev Ram - Online Python training and consulting

Get updates on my software products / ebooks / courses.

Jump to posts: Python   DLang   xtopdf

Subscribe to my blog by email

My ActiveState recipes

FlyWheel - Managed WordPress Hosting



Friday, August 5, 2016

The D Language Playground site

By Vasudev Ram


The D language playground site:


is a web site (created somewhat recently, IIRC), where you can write or paste in a chunk of D code into a text box, click Run, and it will run it on their server, and send back the results to be displayed. It also has a tour of the language, and you can go from one example to another, and just run, or modify and run, each of them. So the same site serves both as an online sandbox to experiment with D language snippets, and as an interactive tutorial for D. In both these ways it is similar to the Go language playground/tour site. Either or both are worth checking out, if you are interested in those languages.

- Vasudev Ram - Online Python training and consulting




My Python posts     Subscribe to my blog by email

My ActiveState recipes



Monday, August 1, 2016

Video: C++, Rust, D and Go: Panel at LangNext '14

By Vasudev Ram

I recently came across this video of a panel discussion (in 2014) on modern systems programming languages. Yes, I know the term is controversial. Andrei and Rob say something about it. See the video.

The languages discussed are: C++, D, Go and Rust, by a panel at LangNext '14.

The panel consisted of key team members from the teams working on those languages:

- Bjarne Stroustrup for C++
- Andrei Alexandrescu for D
- Rob Pike for Go
- Niko Matsakis for Rust

(that's by language name in alphabetical order :)

Here is the video embedded below, and a link to it in case the embed does not work for you (sometimes happens).



I have only watched part of it so far (it is somewhat long), but found it interesting.

You can also download it with youtube-dl (written in Python, BTW) or some other video downloading tool, for watching offline. It's about 1.34 GB in size, so plan accordingly.

- Enjoy.

- Vasudev Ram - Online Python training and consulting
Follow me on Gumroad for product updates:



My Python posts     Subscribe to my blog by email

My ActiveState recipes