A newbie Haskeller revisits Rust

Back in March, I did a comparison between old and new progamming languages. I was very new to Haskell, and knew nothing about Rust. Since then:

  • Haskell has replaced Python as my “go to” language of choice, although for data analysis, I think the Jupyter/Python/Pandas/Matplotlib combination is nearly unbeatable.
  • Rust has had a stable release

My big frustration with Rust was that the add-on libraries were mostly broken due to the lack of stabilisation. Hopefully, that situation will change dramatically. There does seem to be a lot of old Rust documentation about. The community would benefit if the obsolete documentation were to disappear.

I decided to re-evaluate Rust again, to see what the state of play was. I decided to tackle an actual problem: given a file, print a frequency table of the alphabetical characters.

Here’s my Haskell implementation:

import Data.Array
import Data.Char

outputs text =
  let arr = accumArray (+) 0 (0, 255) $ map (\c -> (ord c, 1)) text
      hits =  filter (\(c, qty) -> (isAlpha $ chr c) && (qty > 0) ) $ assocs arr
      map (\(c, qty) -> [chr c] ++ " (" ++ (show qty) ++")") hits

main = do
  text <- readFile "/etc/passwd"
  putStrLn $ unlines $ outputs text

That’s 13 lines of code. Here is my Rust version:

/* frequency.rs
Count the number of alphabetical characters in a file
use std::fs::File;
use std::io::Read;
use std::error::Error;

fn main()
    let f = match File::open("/etc/passwd") // it will be closed automatically     
        Ok(file) => file,
        Err(e) => panic!("Error: {}", Error::description(&e))
    let mut count = [0i32; 255];

    for b in f.bytes() { count[b.unwrap() as usize] += 1 }

    for i in (0u8..128u8) {
        let c: char = i as char;
        let is_alpha: bool = ('a' <= c && c <= 'z') || ('A' <= c && c <= 'Z');
        if is_alpha && (count[i as usize] > 0)  {
            println!("{} ({})", c, count[i as usize]);

That’s 31 lines. In fairness to Rust, I could probably write the code a lot shorter.

It took me longer to write the Rust code, because I was mostly guessing the syntax. I had problems with indexing, until I realised that indices had to be “usize” types. This kind of thing is inevitable when you are dealing with a language that is completely unfamiliar.

Although Haskell is terser, there is probably a lot I am missing about Rust. I think, for example, that “accumArray” could be implemented quite easily in Rust. There’s probably a lot of cross-fertilisation of ideas that can be carried over.

Rust also has a nice “filter_map” function, which does both filtering and mapping. I’m not aware that Haskell has it, but really, it’s just a one-liner to implement in Haskell.

I doubt that Rust could ever be as terse as Haskell. Haskell is a phenomenally terse language, though. Is it more readable? I’m undecided on that anwer as yet.

I have found my Haskell code to be very maintainable. I also like its REPL.

Although I haven’t explored much in the way of Rust’s memory model, I think its mutability is a bit like “gotos”. I don’t mean that perjoratively, either. A judicious use of “mut” can perhaps stop you from racking your brains trying to reduce an algorithm to a purely side-effect free one. The keyword here is “judicious”. By careful control, I think you can still maintain the language’s overall security.

Rust does compile to much smaller binaries, as you might expect. It’s execution also seems faster. What I also like is that I have been able to successfully cross-compile a program to ARM from x64. That has given me some ideas on how I could write utility functions for my cubietruck using my Intel Linux distro.

So, I feel that Rust has a lot of potential, and will be of great interest to Haskellers. I shall probably write my next project in Rust, and see what I think. Will it be able to displace my interest in Haskell, I wonder?


About mcturra2000

Computer programmer living in Scotland.
This entry was posted in Computers and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s