Archive

Archive for the ‘OCaml’ Category

Value capture in Lisp

September 14, 2007 2 comments

In one of my previous posts I’ve told about how (define) works and how (lambda) works. Main difference is that (define) evaluates second argument, and (lambda) doesn’t evaluate anything, it just binds all variables to specific scope. Variables could even be defined after definition of (lambda)! See following example (in Scheme):

>(define f (lambda (x) (+ x y)))

>(f 5)

Error: variable y is not bound.

>(define y 5)

>(f 5)

10

In this example, x is bound to scope of function’s arguments, and y is bound to local scope. Each time the function is applied, it tries to use (evaluate) variable in initially defined scope.

The story continues in OCaml. Now I’m reading a book about this language, and I was surprised to know that it is implemented exactly in the way I was mistakenly thinking about Lisp earlier. So, function definition in OCaml doesn’t capture the scope, it captures the value! Look:

# let a = 10;;
val a : int = 10
# let add2a x = a + x ;;
val add2a : int -> int = <fun>
# add2a 5;;
– : int = 15
# let a = 20;;
val a : int = 20
# add2a 5;;
– : int = 15

So, we have fundamental difference between OCaml and Lisp. I don’t know which behaviour is better, and I don’t bother. I just know how it will behave in both languages. But, my next idea was: is it possible to achieve value capture in Lisp, and scope capture in OCaml ?

Value capture in Lisp is, of course, possible. It is done by using (lambda) inside (let). Look:

>(define x 5)

>(define f
    (let
        ((x1 x))
      (lambda (y) (+ x1 y)))
    )

>(f 5)

10

>(define x 10)

>(f 5)

10

Let allows us to create local scope, and each clause in let is like (define), so it evaluates variable. In this way we achieve value capture in scope accessible only from body of function.

Regarding OCaml: I’m sure that “scope capture” will not work. The reason is that OCaml, unlike Lisp, is a language with static type checking. Since any variable could be re-defined with different type after funciton definition, OCaml implements value capture to avoid type errors.

Advertisements
Categories: Lisp, OCaml, Scheme

Your first and second OCaml programs for Win32

July 3, 2007 Leave a comment

Since “C Programming language” by Kernigan and Ritchie most books about C started with “first program in C” to print “Hello, world!” on console. Windows is so much different from Unix so it even has it’s own “main function” named “WinMain” (instead of “main” for Unix). Because of that huge difference books about programming with Win32API usually start with their own “first program in C for Windows”, simple 5-line program for showing same message using MessageBox function. You can find such examples in book by Petzold and tutorials like this. Let’s make exactly the same program in OCaml.

Program will look like:

open Win32

let _ =
  ignore (message_box null_hwnd “Content of MsgBox” “Caption of MsgBox” [MB_OK]);
  exit 0;

Yes, that’s it, simple. There are no WinMain here, because it’s OCaml, not C. OCaml specifies it’s own entry point to program. WinMain has several arguments; they are available as global variables, however they are stored not by implementation of WinMain, but by invoking some Win32 API functions.

After this simple program books go in different directions. Some books go to windows, message reading/dispatching cycle and window procedures. I prefer to go to dialogs, because first program was also about dialogs. Dialogs are convenient because they could be defined in resources. My second OCaml program for Win32 consists of two files. Here is a OCaml file:

open Win32

let dlg_processors = [
    on_wm_initdialog (fun ~wnd ~msg ~focus ->
        message_return true)
    ;
    on_wm_command (fun ~wnd ~msg ~notify_code ~id ~ctrl ->
        if id == control_id_of_standard IDOK && notify_code == bn_clicked then
           end_dialog ~dlg:wnd ~result:0;
   message_handled
 )
]

let _ =
    try
        ignore (
            dialog_box
                ~inst:the_instance
                ~name:(Rn_string “TestDialog”)
                ~parent:null_hwnd
                ~proc:(standard_dialog_proc ~processors:dlg_processors));

        exit 0

    with
        e ->
            let s = Printexc.to_string e in
            ignore (message_box ~wnd:null_hwnd ~text:s ~caption:”Uncaught exception” ~options:[MB_OK]);
            exit 1

And here is test.rc file:

#include <windows.h>
ABOUTDLG DIALOG 20, 20, 199, 99
STYLE DS_SETFONT |DS_MODALFRAME |WS_POPUP |WS_VISIBLE |WS_SYSMENU |WS_CAPTION
CAPTION “Example caption”
FONT 8, “MS Shell Dlg”
BEGIN
  CONTROL “&OK”,1,”BUTTON”,BS_DEFPUSHBUTTON |WS_CHILD |WS_TABSTOP |WS_VISIBLE ,72,74,40,14
  CONTROL “Hello everybody”,104,”STATIC”,SS_LEFT |WS_CHILD |WS_VISIBLE ,45,14,128,8
  CONTROL “example custom dialog”,105,”STATIC”,SS_LEFT |WS_CHILD |WS_VISIBLE ,45,35,99,8
END

First program used pre-defined generic purpose dialog, second procedure used custom dialog defined in resource file. I hope these two programs will give a good start for everybody who are interested in using OCaml for Win32 programming. Next steps will include making custom resizable Windows with menues, and much more. Unfortunatelly there are not so many information about writing GUI application in OCaml. But maybe with time there will be books even better then one by Petzold!

Categories: OCaml, Windows

Making Win32 GUI programs in OCaml, continued #3. Unsorted thoughts

June 23, 2007 Leave a comment

WordPress shows me report about my blog, and I can see some people come to my blog by making search requests such as “OCaml MFC”. It seems that MFC is most known class library for Windows. Maybe it’s not bad at all. I know it was created at time then C++ was not mature, that’s why MFC contains so many hacks and looks ugly. It also suffers from bad documentation, but it has lots of dedicated books, so it is counted as very well supported. Some people prefer other libraries for C++, such as Qt, wxWidgets, OWL, Ultimate++, SmartWin++. Those libraries are less known and have different focuses, such as open license, productivity, simplicity, cross-platform support. But, as I already stated several times, making OCaml wrapper around some other class library is not an approach I whould take.

One examle of OO widget library for Win32 is a SWT from Eclipse. I now wonder how is it made. I should take my time and investigate.

Thinking about separate compilation. I belive that only reason why this feature is in place is to speed up compilation by compiling only changed files. First users manually specified which files to compile, later tools like make become doing that job.

I’ve also compared Java run-time linking process with loading shared library in C/C++. Java has two ways of loading classes: implicitly, when some class is referenced from another class, and explicitly, by using “Class” class. First approach is simple, second approach gives excellent flexibility such as “plug-ins” and, combined with some ClassLoader magic, allows even using several versions of same library simulteneously. Shared libraries also have these two approaches. Implicit loading of shared library for Windows is very well described here. Dynamic approach for Windows means usage of LoadLibrary()/GetProcAddress()/FreeLibrary() functions.

OCaml has dynamic linking, but only in byte-code mode. It seems that even ocaml-win32 doesn’t support LoadLibrary()/GetProcAddress()

Categories: Java, OCaml, Windows

My second Lisp books

June 23, 2007 Leave a comment

I’m finished reading book of David Touretsky “Common Lisp: a gentle introduction to symbolic computation”. I’m very happy with this book. It’s simple, and explains a large part of library. Now I want to have same knowledge of Scheme library as I have of Common Lisp’s library. That book also explains macros in a simple way. I’m admitting that I was afraid to start reading about macroses because I’ve expected them to be complex to undestand. But finally I feel macroses are simple, and nothing prevents me from writing or using macroses in CL style. However, I know that Scheme has different approach to macroses, and that I still should learn.

I keep comparing “CL: a gentle introduction” book wuth “How to design programs”. “HtDP” doesn’t say anything about library, it explains language itself. However, “HtDP” shows some very advanced tricks, such as abstracting over data by returning “manipulator” function. After reading of “HtDP” I feel myself very clever and confident when I read some articles about functional programming. However, but I fell myself helpless when it comes to writing code. I’m so lazy that I refuse to solve even simple tasks because I don’t want to write code which I expect to be present in library. So I refuse to do anything until I will learn library. I hope my next book, “Scheme language” by Kent Dybvig will complement to my previous books.

I also want to mention article of Paul Graham. When I read it, finally all stuff about lambda got into place in my head. His description of how eval works was exactly what I needed.

If you reading my posts then you see that I have planned myself a lot of reading. Of course I’m not reading several books at once, I’m carefully choosing in which order to read them. I was lucky that I’ve started to learn OCaml after I’ve read some Scheme books. After learning Scheme it’s quite easy to OCaml.

Categories: Lisp, OCaml, Scheme

Making Win32 GUI programs in OCaml, continued #2. Hacking example application and thoughts about separate compilation

June 22, 2007 Leave a comment

Deep in my soul I’m software hacker. Don’t confuse me with crackers: I’m not doing anything which is not legal. When I say hacker I mean a man who likes to play with code for fun. I love to take working program with open code and try to make little changes and see effect. I like to take executable file with closed source and get all available information using tools, for example to see which shared libraries that program uses.

My approach to OCaml is very hackerish. I’ve learned only a small part of language. But I can’t wait, I want to play with language now. I’m playing with ocaml-win32 without solid knowledge of OCaml language itself and I don’t remember much of Win32 programming now. Normal approach whould be to obtain knowledge by reading books and tutorials, then to apply knowledge by development of software. I’m doing those things simultaneously. Probably my way is slower in terms of product. This means that I will produce a working program later then if I whould read first. But my approach is more funny and more enjoyable. That’s why I follow it.

I’m telling that all so everybody could undersand that I’m just a newbie, and they should not trust my opinion in any way. I’m posing this information because I never seen anything else on the topic, and I think that information I’m posting is better than nothing.

After been able to compile ocaml-win32 I was trying to make my own example. I’ve created a separate directory for my own project, copied example file and tried to compile it unchanged. I’ve copied some lines from original Makefile into my own Makefile, and launched it. Imagine my surprise when I’ve got “unbound module Win32” message from compiler! I quickly realised that directory where you try to compile program matters a lot. It took me some time to figure out about .mli files. These files are compiled interface descriptions, and used for separate compilation of modules. In some sense they are similar to .h files of C/C++ language. When I specified path to ocaml-win32 directory using -I option of ocamlc, everything went fine.

This feature led me to thinking about separate compilation in different languages. In Assembler and C/C++ we have “independent compilation”: if you use some function defined in another module you should just declare it in your file, and this function will be marked as “to be resolved” in object file. Linker will search for all such references and bind them to actual implementations. Library authors just make life easier to library users by declaring all their functions in .inc or .h files, and those files are simply concatenated to code of library users. Object code contains unresolved functions in symbolic form, but executable code doesn’t contain it. So, library authors need to write two files each time: library interface and library implementation. Only difference between Assembler and C for me is that in Assembler you don’t need to use .inc file in library implementation, because Assembler procedures don’t need to be declared before they are implemented.

In Java situation is different. Compiler resolves method names at compile time. It uses Java classes compiled into bytecode to check that invokation is syntaxically correct, and includes method’s name in compiled class. Linking in Java happens every time program starts: JVM loads classes, finds names of all classes referenced from just loaded class, loads referenced classes, then binds method invokation to method implementation in memory. Linking at start makes program start a long process, but also allows quick replacement of dependent code as long as method signature remains the same, and also allows some magic like loading code over network on demand. Java linking is similar to dynamic linking in C/Assembler. However, for dynamic linking you still need two files: library implementation and library interface, but in Java you need only compiled class files.

Supporting two files in C is a pain. Also textual representation of interface makes compilation slow: each time interface is used it should be loaded and parsed. Some compilers have a workaround by using pre-compiled headers, but I think that’s overcomplication. In Java you have another pain: code should be compiled in strict order, all code on which your classes depend should be compiled before. That’s possible for C to have a single file, and generate .h files on the fly, making it similar to Java. Also problem of Java approach is that class files are big, because they contain all information nesessary for linking.

OCaml also has separate compilation. Each compilation unit has interface. Interface could be specified explicitly, but if they are not specified then everything is availabe through interface. Interfaces are compiled in exactly the same way as implementations. When some module uses another module it requires only compiled module interface for it’s compilation. So, this approach is something between C and Java: you can have one or two files for source code, two files will be produced as result of compilation. Then some module uses library, it requires only compiled interface for compilation, and compiled implementation will be used when all compiled modules linked together. Compiled interfaces are faster then .h files because they are parsed faster, and they are faster then Java classes because they are smaller. Java approach is little easier because you don’t need to specify both compiled interface and compiled implementation.

Well, that’s all my thoughts about separate compilation for now. Back to my OCaml fun.

Then I was able to compile unchanged example application in separate folder, I’ve started to make small changes to it. By looking at the code I’ve started to remember all messy details about Win32 programming: program’s message loop, Window class, Window procedure, working with program resources, specifying brushes. I was able to edit resource definition file and add new icon. After that I was able to specify to main window to use that icon by editing definition of main window class. I was also able to change background color for main window. Without knowledge of OCaml I can’t go further. However, I’m quite happy with progress I was able to made.

Now I need to learn more about OCaml language itself, about it’s standard library. And I should also refresh all my knowledge about Win32API. For OCaml I have all free books. For Win32 I have books of Petzold and Richter.

After playing with ocaml-win32 I think that using only that library is be too complex way of development. OCaml is OO language, so some library should be build on top of low-level API. I still believe that ocaml-win32+class library written in OCaml is right approach, better then OCaml wrapper over OO widget library written in C++ (like SmartWin++, Tk, wxWidgets, and others). There is a library for OCaml named “osiris”. However, it compiles with error, and I don’t know OCaml good enough to fix it myself now.

Categories: OCaml, Windows

Making Win32 GUI programs in OCaml, continued #1. Native compilation

June 19, 2007 1 comment

I keep playing with OCaml, and it’s very fun.

First funny thing is that OCaml could be used to compile C/C++ files. Of course, it doesn’t contain C compiler inside, it invokes some external compiler. Which compiler to invoke depends on version of OCaml, for Windows it supports Microsoft Visual C++ and MinGW. Thos e compilers should be possible to locate via PATH, because OCaml simply invokes “gcc” or “cl”. Why such feature is implemented – I don’t know, because compiler could always be invoked directly. Probably OCaml adds it’s own include and libary directories for compiler and linker.

OCaml can produce two types of code: byte-code and native code. Byte code available for much wider range of platforms then native code. Byte code files are very similar to object files produced by C compiler: they have extensions .cmo, they could be organized in libraries (they have extensions .cma). Byte code files could be executed by OCaml virtual machine called “ocamlrun”. Compiler is also able to produce stand-alone executables which contain both virtual machine runtime and byte code for your program. Such stand-alone program is usual exe file and could be executed on any Windows machine. In this case linker is invoked (from MinGW or Microsoft Visual C++). Stand-alone programs also able to contain staticaly-linked object code, written in C/C++ or assembly.

Native compiler produces native code. It does that in two-step approach: first, assembly source generated, then external assembler is invoked for compilation. OCaml version for Microsoft Visual C++ invokes Microsoft Assembler (ml.exe), so it is required for native compilation. I didn’t checked that, but I suppose that Ocaml version for MinGW invokes GNU assembler. After compiling all modules are linked using external linker. Native executables are also stand-alone, and they are usually faster then byte-code.

I’ve discovered that by playing with ocaml-win32. By default only byte-code version of library is compiled. To compile native version of library, I’ve invoked “nmake win32.cmxa”, and got “command not found: ml.exe”. So I’ve downloaded Microsoft Assembler and then everything were build succesfully.

I like OCaml more and more. It’s approach to compilation seems very good to me. And ability to interface C makes it very powerful.

Categories: OCaml, Windows

Making Win32 GUI applications in OCaml

June 15, 2007 3 comments

In my recent article I was talking about my attempts to find language other that C/C++ for writing GUI applications. Well, I should admit that last time I did GUI application myself was 5 years ago. It was written in C++ and used MFC. All last time I did only server-side programming. Only now I need to write a new GUI application, and I want this application to be written in programming language other than C/C++, so I could practice that language.  So, I didn’t GUI programing for long time, so my opinion about languages, libraries and graphical toolkits is not very solid. But I’m windows user, and I have my opinion about GUI programs that I use. For me very important things about GUI program is that UI should look native and be fast, and that it should be small and launch quickly. That makes external impression about program.

Nowdays almost everybody use some object-oriented wrapper library around Windows ui.dll, because it simplifies development greatly. I know a good wrapper for C++, called SmartWin++, but I never used it myself seriously. I’ve just downloaded it and tried to build example applications. Executables are small and fast, and UI looks native. Code for applications is small and clean, especially compared to MFC-oriented applications. At last, SmartWin++ could be used with both Microsoft Visual C++ compiler and with MinGW compiler, which is also important for me. Probably soon they will add support for other compilers. All those things make me happy with SmartWin++ library if I choose C/C++ as implementation language.

Making access to Win32 UI library for other languages is more difficult, because there should be a binding to C for each function. Taking into account size of Win32API it’s a huge task. So, people who develop other languages usually do binding to some simplified wrapper around ui.dll. Microsoft did that for Visual Basic. Borland did that for Delphi. Perl, Python and OCaml have bindings to wxWidgets.

Some words about wxWidgets. It’s good library, and could be used for fast application development in C++, because it’s much simpler to use then raw Win32 UI API, and easier than MFC. For me the only problem of wxWidgets is that it’s not just object-oriented wrapper around Win32 UI, but cross-platform library with wrappers around lots of platform-specific toolkits. I don’t like this idea, and prefer SmartWin++.

So, finally, I came to conclusion: when you develop GUI, you don’t choose the language which you like, but choose the language which has best libraries for that GUI.

In abovementioned article I told that OCaml is very Unix-biased. I’m apologising for that, I was wrong. OCaml has good support for windows sockets and threads in standard library, but it also has good binding to Win32API as additional library. This makes it perfectly suitable for development of native Win32 UI applications. However, this path is not easy at the beginning. Here I whould like to share my own experience, hoping it will save somebody’s time.

First, few words about OCaml. For Win32 it’s available in three flavours: CygWin, MinGW and Microsoft Visual C++. Initially I thought that it means that those compilers were used to compile OCaml tools. That’s right, but also that means that those compilers will be used by OCaml tools themselves to compile your source code. If you installing MinGW version, you should have MinGW itself installed. If you installing Visual C++ version, then you should have Visual C++. Fortunatelly, both compilers are available for free. This additional requirement for C compiler was not obvious for me, and I’ve spent some time trying to figure it out.

If you want to use ocam-win32 library, you must have version of OCaml for Visual C++. I hope someday this library could be also built from MinGW.

Library is available in source form from here. Unzip it in any place, and you will have lots of sources in both C and Ocaml, together with several small text files. Those files are not very helpfull, so it’s not easy to figure out what to do. Finally I understood that I should make library myself. The only toolkit I had was MinGW, so I’ve tried to invoke “make”, but received “delimeter absent” error, because Makefile used spaces instead of tabs. After some time I’ve realized that I need Visual C++. I’ve installed free compiler and tried to build it by invoking nmake. No complains about delimeters this time, but OCaml kept invoking gcc, which complained about compiler keys. So I undestood that I need version of OCaml built for Visual C++. That was not obvious.  I’ve re-installed OCaml, and run nmake again. Better this time, now it was complaining about missing headers. It occured that I should have Microsoft Platform SDK installed. It’s big, so I’ve installed only Platform core SDK.  To correctly compile a lots of environment variables should be set correctly. Include directories should contain both Visual C++ runtime headers and Platform SDK headers. The same story for libraries. I was able to do that by first invoking “set environment” script of Protocol SDK, then, from same command prompt, invoking vcvars32.bat. Another attempt to compile, and this time it was complaining about missing “shlwapi.h” file. After some googling I’ve found that I should install not just Platform core SDK, but also IE SDK. I did that, and, finally, got the library!

There is a test application, which starts very fast and looks native. So, now I’m quite optimistic about usage of OCaml for GUI applications for Win32 platform. OCaml seems much easier language than C++.

Many thanks to authors of this library. I had lots of problems during installation because it’s a long time since I’ve last used Visual C++, and because library is  for hackers who know that to do. Library authours should extend their readme files, and they should also redistribute compiled versions of libraries.

Update: this article is a first one dedicated to GUI programming in OCaml. See subsequent posts which will describe by progress on the path. That’s not a tutorial, just information written by newbie, so don’t trust me.

Categories: OCaml, Windows