Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Well-typed Vignettes

DZone's Guide to

Well-typed Vignettes

I present to you some well-typed programs along with associated run-time and compile-time errors for pondering the meaning of the phrase "Well-typed programs cannot go wrong."

· Web Dev Zone ·
Free Resource

Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

I present to you some well-typed programs along with associated run-time and compile-time errors for pondering the meaning of "well-typed". For context, I was trying to understand the meaning of the quote “Well-typed programs cannot go wrong.” The exercise was illuminating for me, but when I started writing explanations they got a little too philosophical, so I’m just going to present the code and the errors.

Ruby

puts File.read(ARGV[0])

Errno::ENOENT

If the file does not exist then there is nothing to do. All programming languages no matter how good their type system can not reason about what is external to them and so the sane thing to do is throw an error and halt or let the programmer do something with that error. In Ruby’s case it does the right thing and throws an exception:

main.rb:1:in 'read': No such file or directory @ rb_sysopen - asdf (Errno::ENOENT)
  from main.rb:1:in '<main>'

TypeError

Contrary to popular belief Ruby actually has static types it’s just that nothing is done with them until run-time. When an argument of the wrong type is passed to a method we get a type error. The difference is that in a more statically typed language the error would be during compile-time instead of run-time:

def to_stdout(filename)
  puts File.read(filename) 
end
to_stdout(1)
main.rb:2:in 'read': no implicit conversion of Fixnum into String (TypeError)
  from main.rb:2:in 'to_stdout'   
  from main.rb:4:in '<main>'

Haskell

import System.IO 
import System.Environment   

dumpContents :: FilePath -> IO () 
dumpContents fileName = openFile fileName ReadMode >>=   
  hGetContents >>= putStrLn   

main :: IO () 
main = getArgs >>= \args -> dumpContents (args !! 0)

Prelude.(!!): index too large

Just as in the Ruby case, Haskell will throw a run-time exception when assumptions about the external world fail. If I don’t pass enough arguments then we get a run-time error:

main: Prelude.(!!): index too large

openFile: does not exist (No such file or directory)

Similarly, if I pass an argument that corresponds to a file that does not exist we again get a run-time error:

main: asdf: openFile: does not exist (No such file or directory)

Notice that up to this point both Haskell and Ruby have failed in exactly the same way with run-time errors.

Couldn’t match type ‘[Char]’ with ‘Char’

So, this is the one case where Haskell does one better than Ruby. When I pass the wrong argument to dumpContents instead of getting a run-time error the compiler tells me that something is not lining up properly:

[1 of 1] Compiling Main             ( main.hs, main.o )
main.hs:9:43:
Couldn't match type ‘[Char]’ with ‘Char’
    Expected type: FilePath
      Actual type: [String]
    In the first argument of ‘dumpContents’, namely ‘(args)’
    In the expression: dumpContents (args)

TypeScript

All of the same things happen with TypeScript except we get to choose how strongly we want to enforce certain constraints. These days TypeScript is my go-to choice for all things related to JavaScript.

/// <reference path="/home/david/Downloads/node.d.ts"/>
var fs = require('fs');
fs.readFile(process.argv[2], (error : string, data : Buffer) => {
  console.log(data.toString());
});

TypeError: path must be a string

fs.js:491
  binding.open(pathModule._makeLong(path),
    ^ 
TypeError: path must be a string
    at TypeError (native)     
    at Object.fs.open (fs.js:491:11)     
    at Object.fs.readFile (fs.js:262:6)     
    at Object.<anonymous> (/home/david/test/main.js:3:4)     
    at Module._compile (module.js:460:26)     
    at Object.Module._extensions..js (module.js:478:10)     
    at Module.load (module.js:355:32)     
    at Function.Module._load (module.js:310:12)     
    at Function.Module.runMain (module.js:501:10)     
    at startup (node.js:129:16)

TypeError: Cannot read property ‘toString’ of undefined

/home/david/test/main.js:4
    console.log(data.toString());
                    ^
TypeError: Cannot read property 'toString' of undefined
    at /home/david/test/main.js:4:21
    at fs.js:263:20
    at FSReqWrap.oncomplete (fs.js:95:15)


Deploy code to production now. Release to users when ready. Learn how to separate code deployment from user-facing feature releases with LaunchDarkly.

Topics:
ruby ,haskell ,typescript ,web dev ,code snippets

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}