Wednesday, 27 May 2015

Print Working Directory

How about a tiny program that does something useful: that is, tells me what directory I am currently in...

If you simplify your DOS prompt:

>prompt $G

then it doesn't show you but it does leave more space for typing.

Right.  The program looks like this:-

module Main

import System.Directory(getCurrentDirectory)

main = do
  pwd <- getCurrentDirectory
  putStr pwd

This goes in a file main.hs and defines the main indeed only module with the entry point main.

To get access to the required system call we import the system library called System.Directory but specify (in the brackets) that the only reference we want to make is to the function getCurrentDirectory.

Now our main function consists of two IO actions that are stacked one on top of the other inside the do construct, which has the overall effect of taking the first action and then the second.

The first action calls the system function getCurrentDirectory and assigns the identifier pwd to the result.

The type of getSystemDirectory is

getCurrentDirectory :: IO FilePath

In other words it's an IO action that returns a value of type FilePath - and FilePath is just a synonym for the String type, so we can display this without further manipulation using a function that takes a string parameter.

So the second action prints the value of pwd to the terminal.

ok now to compile - compile the file main.hs and specify the output file to be called pwd.exe:

 Volume in drive C has no label.
 Volume Serial Number is 6496-80C4

 Directory of C:\Users\polly\Documents\Projects\Haskell\pwd

20/05/2015  21:17    <DIR>          .
20/05/2015  21:17    <DIR>          ..
20/05/2015  21:17               131 main.hs
20/05/2015  21:04               112 main.hs~
20/05/2015  21:16             1,389 notes.txt
20/05/2015  21:14             1,309 notes.txt~
               4 File(s)          2,941 bytes
               2 Dir(s)  273,825,931,264 bytes free

>ghc main.hs -o pwd.exe
[1 of 1] Compiling Main             ( main.hs, main.o )
Linking pwd.exe ...

Now I can run it and see my working directory:


No comments:

Post a Comment