text:
Shortest a -> b -> (a -> b) function in Haskell
I got the following question at a test:

Write a function f with the following type a -> b -> (a -> b). a and b should not be bound in any sense, the shorter the code, the better.

I came up with f a b = \x -> snd ([a,x],b). Can you find something tinier?
Currently the winner is: f _=(.f).const

If a more general type is allowed: f = const const.

@hammar: or f _ b _ = b, but, given the solution in the question, I suspect a more general type is not allowed.

If a more general type is allowed, why not f = id?

In fact if a more general type is allowed then f = f is a solution, so I guess the conditions on the type are very important!

A more general type is not allowed, your assumptions were correct.

If you're allowed to import Control.Applicative, you can replace const by pure, which is one character less.

Can the answer be a partial function?

Your example can be shrunk by getting rid of the anonymous function on the right-hand side:
f a b x = snd ([a,x],b)

This works because the type a -> b -> a -> b is equivalent to a -> b -> (a -> b) in Haskell.

Slightly shorter modification: f a b x = snd (f x,b)

The function f _=(.f).const is actually of a more general type than f :: a -> b -> (a -> b), namely f :: a -> b -> (c -> b). If no type signature is given, the type inference system infers a type of f :: a -> b -> (a -> b), but if you include the type signature f :: a -> b -> (c -> b) with the exact same definition, Haskell will compile it without issue and will report consistent types for the partial applications of f. There is probably some deep reason why the type inference system is stricter than the type checking system in this case, but I don't understand enough category theory to come up with a reason as to why this should be the case. If you are unconvinced, you are welcome to try it yourself.

might be like the case of f a b = f a a. it infers to be of type a -> a -> b although it complies with the type a -> b -> c. it is because if f is not given a type it can only use itself monomorphically.

i don't think this should matter though

Given ScopedTypeVariables, I came up with this:
f (_::a) b (_::a) = b

If you shrink down both my function and yours, mine is a hair shorter:
f(_::a)b(_::a)=b
f a b x=snd([a,x],b)

Of course, you're probably not allowed to rely on ScopedTypeVariables :P.

This is not as short as f _=(.f).const (due to Sassa NF). Which also doesn't need ScopedTypeVariables.

Hmm, I initially thought this would require the first and third arguments to be lists...

@ChrisTaylor: Too much OCaml on the mind? :)

Hah, must be! ;)

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Code Romanization
The challenge is to make any Roman numerals valid code in your chosen language.
They should not appear inside of strings or anything similar, but work just like any other tokens, literals such as (Arabic) numbers, characters or strings; or  variable/method/function identifiers, etc.
For instance, in Java, the following would have to compile and run just as if i was initialized to 42:
int i = XLII;

The actual parsing of the numerals is secondary, so you can use a library if you want to, but this is a popularity contest, so creativity is encouraged.
You cannot use any language that actually uses roman numerals, if there is such a thing.
Good luck.

So, we need to write an extension to the language, thereby creating a new one?

@KendallFrey That depends on the language you choose I guess. But I wouldn't recommend building a new Java compiler.

I don't know if there is an alternative for Java (and most other languages).

I used Java as an example for the hell of it ;) and @histocrat just delivered an awesome Ruby example, so no more complaining!

I'll complain if I want to, because the languages I use are not extensible like that, so I can't even participate.

Sure you can't tap into the runtime somehow..?

At compile-time? Unlikely. :P

@KendallFrey The source would have to compile and run. For Java, you could write a "compiler" that edits the source, then programmatically compiles. One way of such compiling is through running a Process

@Quincunx I too thought of something like this, but as the poster of the question I didn't want to give to anything away. The post you refer to shouldn't be very far away from a valid answer here. I am also thinking about relaxing the requirements a little though, so that the roman numerals wouldn't need to behave exactly like other numbers, but for example could be used like Numeral n = new XLII() - as long as the numeral itself in not contained in a string or other literal . That could probably be helpful in some languages.

@daniero That would be weird; it would require hard-coding the classes for every roman numeral (not possible, there are infinite roman numerals). Something like Numeral n = new Numeral("XLII"); makes more sense. I don't think you should change your question though.

@Quincunx You're right. I was thinking that since we already were into compiled languages and toying with reflection, one could do some static analysis to figure out just which numerals one would need to make a class for. But it doesn't actually make much sense since you could rather use the analysis to figure out what constants to create. new Numeral("XLII") would be against the rules either way.

Seems boring in most languages. For example in python I would simply write a script that uses ast to parse the source. Insert at the top of the AST the definition of the roman numerals from 1 to 3999. Compile the whole thing and run it. It's just boring to write the code to handle the process.

@Bakuriu and your comment is boring too. This is a popularity contest, so you should try to come up with something fun. I think there are some nice answers here that are more imaginative (than compiling a scripting language).

@Quincunx an old blog post about someone doing that... but rather closer to the compiler than a separate thing.  http://www.iam.unibe.ch/~akuhn/blog/2008/roman-numerals-in-your-java/

My language has a function that does exactly this but to input. (The language was created after this challenge). Can I use this e.g take input and convert?

@ValyrioAccount I'm fine with a newer language as long as you state it in the answer. The problem to me is that it sounds like you wouldn't be answering the question properly -- This is not really about the actual conversion from Roman numerals, but rather about finding a way to alter the language itself in a way so that it accepts Roman numerals as code. If I'm wrong then go ahead :)

C
There are only so many Roman numerals, since 4000 and higher have no standard notation, and the preprocessor is a wonderful decompression tool, especially if you have no problems with the fact that the code has undefined behaviour.
enum{_
#define a_
#define d_
#define g_
#define j_
#define a(x)c(x)b
#define b(x)c(x)a
#define c(x)x,
#define d(x)f(x)e
#define e(x)f(x)d
#define f(x)m(a(x)(x##I)(x##II)(x##III)(x##IV)(x##V)(x##VI)(x##VII)(x##VIII)(x##IX))
#define g(x)i(x)h
#define h(x)i(x)g
#define i(x)m(d(x)(x##X)(x##XX)(x##XXX)(x##XL)(x##L)(x##LX)(x##LXX)(x##LXXX)(x##XC))
#define j(x)l(x)k
#define k(x)l(x)j
#define l(x)m(g(x)(x##C)(x##CC)(x##CCC)(x##CD)(x##D)(x##DC)(x##DCC)(x##DCCC)(x##CM))
#define m(x)n(x)
#define n(...)__VA_ARGS__##_
m(j()(M)(MM)(MMM))
};

This defines all Roman numerals from I to MMMCMXCIX as enumeration constants, plus _ (which can be replaced by anything you like) as zero.

Absolutely brilliant, propose adding it to the next C release (C2X?) as <roman.h>! With %r and %R printf formats!

I thought i know how to use the preprocessor, until now :|
Could you update your answer with a minimal usage example of this enum?

@YiminRong And scanf too :) @klingt.net I'm not sure what sort of example you're looking for. A fairly simple one would be int main() { return MMMCMXCIX - M - M - M - CM - XC - IX; }

I like the idea, but why did you opt to go with undefined behavior when defined behavior was fairly simple? Not judging, just curious?

@CasaDeRobison For fun, mainly. I like it because it is one of the very few cases of undefined behaviour at preprocessing time that isn't flagged as an error by current compilers, and likely won't be in the future. I don't ever write anything like that in code that's meant to be useful, but code posted here isn't meant to be useful, so what better occasion to try it?

Fair enough. I'm certainly not above doing such things myself, reading it just made my eyes bleed a little. ;)

Ruby
def Object.const_missing(const)
  i = const.to_s
  if i =~ /^[IVXLCDM]+$/
    #http://codegolf.stackexchange.com/questions/16254/convert-arbitrary-roman-numeral-input-to-integer-output
    %w[IV,4 IX,9 XL,40 XC,90 CD,400 CM,900 I,1 V,5 X,10 L,50 C,100 D,500 M,1000].map{|s|k,v=s.split ?,;i.gsub!(k,?++v)}
    eval(i)
  else
    super
  end
end

Any (uppercase) Roman numerals will now be parsed like their decimal equivalents. The only issue is that they're still assignable: you can do X = 9, but not 10 = 9. I don't think there's a way to fix that.

This is perfect. The assignment thing is not an issue; You can use assignments to do all sorts of stupid things.

JavaScript (ES6)
Use Proxy to catch roman numerals.
Testable in Firefox (latest) on JSFiddle.
Not testable in Chrome (with Traceur) since Proxy implementation is broken.
// Convert roman numeral to integer.
// Borrowed from http://codegolf.stackexchange.com/a/20702/10920
var toDecimal = (s) => {
  var n = 0;
  var X = {
    M: 1e3, CM: 900, D: 500, CD: 400, C: 100, XC: 90,
    L: 50,  XL: 40,  X: 10,  IX: 9,   V: 5,   IV: 4,  I: 1
  };

  s.replace(/[MDLV]|C[MD]?|X[CL]?|I[XV]?/g, (d) => n += X[d]);
  return n;
};

// Whether a string is a valid roman numeral.
var isRoman = (s) => s.match(/^[MDCLXVI]+$/);

// Profixy global environment to catch roman numerals.
// Since it uses `this`, global definitions are still accessible.
var romanEnv = new Proxy(this, {
  get: (target, name) => isRoman(name) ? toDecimal(name) : target[name],
  set: (target, name, value) => isRoman(name) ? undefined : (target[name] = value),
  has: (target, name) => isRoman(name) || name in target,
  hasOwn: (target, name) => name in target
});

Usage:
with (romanEnv) {
  var i = MIV + XLVIII;
  console.log(i); // 1052
}

C & C++ (Updated Answer)
As observed in a comment, my original solution had two problems:

Optional parameters are only available in C99 and later standards of the language family.
Trailing comma in enum definition is also specific to C99 and later.

Since I wanted my code to be as generic as possible to work on older platforms, I decided to take another stab at it. It is longer than it was before, but it works on compilers and preprocessors set to C89/C90 compatibility mode. All macros are passed an appropriate number of arguments in the source code, though sometimes those macros "expand" into nothing.
Visual C++ 2013 (aka version 12) emits warnings about missing parameters, but neither mcpp (an open source preprocessor that claims high compliance with the standard) nor gcc 4.8.1 (with -std=iso9899:1990 -pedantic-errors switches) emit warnings or errors for those macro invocations with an effectively empty argument list.
After reviewing the relevant standard (ANSI/ISO 9899-1990, 6.8.3, Macro Replacement), I think there is sufficient ambiguity that this should not be considered non-standard. "The number of arguments in an invocation of a function-like macro shall agree with the number of parameters in the macro definition...". It does not seem to preclude an empty argument list as long as the needed parentheses (and commas in the case of multiple parameters) are in place to invoke the macro
As for the trailing comma problem, that is resolved by adding an extra identifier to the enumeration (in my case, MMMM which seems as reasonable as anything for the identifier to follow 3999 even if it doesn't obey the accepted rules of Roman numeral sequencing exactly).
A slightly cleaner solution would involve moving the enum and supporting macros to a separate header file as was implied in a comment elsewhere, and using undef of the macro names immediately after they were used so as to avoid polluting the namespace. Better macro names should undoubtedly be chosen as well, but this is adequate for the task at hand.
My updated solution, followed by my original solution:
#define _0(i,v,x)
#define _1(i,v,x) i
#define _2(i,v,x) i##i
#define _3(i,v,x) i##i##i
#define _4(i,v,x) i##v
#define _5(i,v,x) v
#define _6(i,v,x) v##i
#define _7(i,v,x) v##i##i
#define _8(i,v,x) v##i##i##i
#define _9(i,v,x) i##x

#define k(p,s) p##s,
#define j(p,s) k(p,s)
#define i(p) j(p,_0(I,V,X)) j(p,_1(I,V,X)) j(p,_2(I,V,X)) j(p,_3(I,V,X)) j(p,_4(I,V,X)) j(p,_5(I,V,X)) j(p,_6(I,V,X)) j(p,_7(I,V,X)) j(p,_8(I,V,X)) j(p,_9(I,V,X))
#define h(p,s) i(p##s)
#define g(p,s) h(p,s)
#define f(p) g(p,_0(X,L,C)) g(p,_1(X,L,C)) g(p,_2(X,L,C)) g(p,_3(X,L,C)) g(p,_4(X,L,C)) g(p,_5(X,L,C)) g(p,_6(X,L,C)) g(p,_7(X,L,C)) g(p,_8(X,L,C)) g(p,_9(X,L,C))
#define e(p,s) f(p##s)
#define d(p,s) e(p,s)
#define c(p) d(p,_0(C,D,M)) d(p,_1(C,D,M)) d(p,_2(C,D,M)) d(p,_3(C,D,M)) d(p,_4(C,D,M)) d(p,_5(C,D,M)) d(p,_6(C,D,M)) d(p,_7(C,D,M)) d(p,_8(C,D,M)) d(p,_9(C,D,M))
#define b(p) c(p)
#define a() b(_0(M,N,O)) b(_1(M,N,O)) b(_2(M,N,O)) b(_3(M,N,O))

enum { _ a() MMMM };

#include <stdio.h>

int main(int argc, char** argv)
{
    printf("%d", MMMCMXCIX * MMMCMXCIX);
    return 0;
}

The original answer (which received the first six upvotes, so if no one ever upvotes this again, you shouldn't think my updated solution got the upvotes):
In the same spirit as an earlier answer, but done in a way that should be portable using only defined behavior (though different environments don't always agree on some aspects of the preprocessor). Treats some parameters as optional, ignores others, it should work on preprocessors that don't support the __VA_ARGS__ macro, including C++, it uses indirect macros to ensure parameters are expanded before token pasting, and finally it is shorter and I think easier to read (though it is still tricky and probably not easy to read, just easier):
#define g(_,__) _, _##I, _##II, _##III, _##IV, _##V, _##VI, _##VII, _##VIII, _##IX,
#define f(_,__) g(_,)
#define e(_,__) f(_,) f(_##X,) f(_##XX,) f(_##XXX,) f(_##XL,) f(_##L,) f(_##LX,) f(_##LXX,) f(_##LXXX,) f(_##XC,)
#define d(_,__) e(_,)
#define c(_,__) d(_,) d(_##C,) d(_##CC,) d(_##CCC,) d(_##CD,) d(_##D,) d(_##DC,) d(_##DCC,) d(_##DCCC,) d(_##CM,)
#define b(_,__) c(_,)
#define a       b(,) b(M,) b(MM,) b(MMM,)
enum { _ a };

+1, but note that the use of empty macro arguments, and the comma at the end of an enumerator list, are both new features of C99 and C++11, and both C99 and C++11 do support __VA_ARGS__.

Dang if you're not right! I guess I've been seeing this used as extensions all this time. Ah well. :)

Common Lisp
The following is a rather lengthy explanation of how I made a macro that you can use like this:
(roman-progn
  (+ XIV XXVIII))

When a macro is called in Common Lisp, it basically acts like a function, only that the arguments are received before they are evaluated. Actually, since in Common Lisp code is just data, what we receive is a (nested) list representing an unparsed syntax tree that we can do whatever we want with, and it's done in compile-time.
Helper functions
The first step of the plan is to take this tree and scan it for anything that looks like Roman Numerals. This being Lisp and all, let's try to do it somewhat functionally: We need a function that will do a deep traversal of a tree and return every object for which a provided function searchp returns true. This one is even (semi) tail-recursive.
(defun deep-find-all (searchp tree &optional found)
  (if (null tree)
    found
    (let* ((item (car tree))
           (new-found (if (consp item)
                        (deep-find-all searchp item found)
                        (if (funcall searchp item)
                          (cons item found)
                          found))))

      (deep-find-all searchp (cdr tree) new-found))))

Then some code for parsing the roman numerals, courtesy of Rosetta Code:
(defun mapcn (chars nums string)
  (loop as char across string as i = (position char chars) collect (and i (nth i nums))))

(defun parse-roman (R)
  (loop with nums = (mapcn "IVXLCDM" '(1 5 10 50 100 500 1000) R)
        as (A B) on nums if A sum (if (and B (< A B)) (- A) A)))

The actual macro
We take the syntax tree (body), search it with our deep-find-all procedure and somehow make the roman numerals that we find, available.
(defmacro roman-progn (&body body)
  (let* ((symbols (deep-find-all (lambda (sym)
                                   (and
                                     (symbolp sym)
                                     (loop for c across (string sym)
                                           always (find c "IVXLCDM")))) body))
         (parsed-romans (mapcar (lambda (sym)
                                  (list sym (parse-roman (string sym)))) symbols)))

    (if parsed-romans
      `(let (,@parsed-romans)
         ,@body)
      `(progn
         ,@body))))

So, what is 1 + 2 + 3 + (4 * (5 + 6)) + 7 ?
(roman-progn
  (+ I II III (* IV (+ V VI)) VII))
=> 57

And to see what actually happened when the macro was invoked:
(macroexpand-1 +)
=> (LET ((VII 7) (VI 6) (V 5) (IV 4) (III 3) (II 2) (I 1))
   (+ I II III (* IV (+ V VI)) VII))

Lua
setmetatable(_G, {
    __index = function(_, k)
        if k:match"^[IVXLCDM]*$" then
            local n = 0
            for _, v in ipairs{{IV = 4}, {IX = 9}, {I = 1}, {V = 5}, {XL = 40}, {X = 10}, {XC = 900}, {CD = 400}, {CM = 900}, {C = 100}, {D = 500}, {M = 1000}} do
                local p, q = next(v)
                local r
                k, r = k:gsub(p, "")
                n = n + r * q
            end
            return n
        end
    end
})

Simply a fallback __index for the global table. The actual conversion using gsub turned out much prettier than I imagined it to be.

Smalltalk (Smalltalk/X) (87/101 chars)
of course we could easily modify the parser's tokenizer (as it is part of the class library, and as such open for modification, and always present), but a challenge is to affect only evaluations in a given context, so that the rest of the system works as usual.
Version 1:
define a number of variables in the evaluation namespace. So this will affect interactive doIts (aka evals):
(1 to:3999) do:[:n |
    Workspace workspaceVariables at:(n romanPrintString asUppercase) put:n]

then I can do (in a doIt, but not in compiled code):
   |a b|
   a := MMXIV.
   b := V.
   a + b

-> 2019
Notice: the 101 chars includes whitespace; actually it can be done with 87 chars.
Also notice, when define in the global Smalltalk namespace,
I'd see those constants also in compiled code.
Version 2:
Use a methodWrapper hook, which allows for any existing code to be wrapped without recompiling. The following wraps the Parser's tokenizer to look for a roman identifier to be scanned and makes it an integer. The tricky part is to dynamically detect if the calling context is from the roman empire or not. This is done using a query signal (which is technically a proceedable exception):
define the query:
InRomanScope := QuerySignal new defaultAnswer:false.

So we can ask at any time ("InRomanScope query") to get false by default.
Then wrap the scanner's checkIdentifier method:
MessageTracer
    wrapMethod:(Scanner compiledMethodAt:#checkForKeyword:)
    onEntry:nil
    onExit:[:ctx :ret |
        InRomanScope query ifTrue:[
            |scanner string token n|

            scanner := ctx receiver.
            string := ctx argAt:1.
            (n := Integer readFromRomanString:string onError:nil) notNil
            ifTrue:[
                scanner "/ hack; there is no setter for those two
                    instVarNamed:'tokenType' put:#Integer;
                    instVarNamed:'tokenValue' put:n.
                true
            ] ifFalse:[
                ret
            ].
        ] ifFalse:[
            ret
        ]
    ].

Now the scanner works as usual, unless we are in the roman empire:
InRomanScope answer:true do:[
    (Parser evaluate:'MMDXXV') printCR.
].

-> 2525
we can even compile code:
Compiler
    compile:'
        inTheYear2525
            ^ MMDXXV
    '
    forClass:Integer.

nice try; but this fails with a syntax error (which is exactly what we want).
However, in the roman empire, we CAN compile:
InRomanScope answer:true do:[

    Compiler
        compile:'
            inTheYear2525
                ^ MMDXXV
        '
        forClass:Integer.
]

and now, we can ask any integer (sending that message) from inside and outside of Rome:
(1000 factorial) inTheYear2525

-> 2525

Nice to see Smalltalk!

Postscript
I tried to follow the C one but I didn't understand it. So I did it this way:
/strcat{
    2 copy length exch length add string % 1 2 3
    3 2 roll % 2 3 1
    2 copy 0 exch putinterval % 2 3 1
    2 copy length % 2 3 1 3 n(1)
    5 4 roll putinterval % 3 1
    pop
}def
/S{
    dup length string cvs
} def
[
/u {/ /I /II /III /IV /V /VI /VII /VIII /IX}
/t {/ /X /XX /XXX /XL /L /LX /LXX /LXXX /XC}
/h {/ /C /CC /CCC /CD /D /DC /DCC /DCCC /CM}
/m {/ /M /MM /MMM /MMMM}
>>begin
[0
[
[m]{ % M*
    S
    [h]{ % M* H*
        S
        [t]{ % M* H* T*
            S
            [u]{ % M* H* T* U*
                S
                4 copy
                strcat strcat strcat % M* H* T* U* M*H*T*U*
                5 1 roll % M*H*T*U* M* H* T* U*
                pop % (M*H*T*U*)* M* H* T*
            }forall
            pop % (M*H*T*U*)** M* H*
        }forall
        pop % (M*H*T*U*)*** M*
    }forall
    pop % (M*H*T*U*)****
}forall
]
{exch dup 1 add}forall pop>>end begin

Postscript doesn't have enum but we can construct a dictionary with sequential integer values and fold them into an array. This reduces the problem to generating all the strings in sequence, which is done by concatenating in 4 nested loops. So it generates all the strings, then interleaves each string with an increasing counter value, resulting in a long series of <string> <int> pairs on the stack which are wrapped in <<...>> to produce a dictionary object.
The program constructs and installs a dictionary mapping all names for the roman numerals to their corresponding value. So mentioning the names in source text invokes the automatic name-lookup and yields the integer value on the stack.
II IV MC pstack

prints
2
4
600

D
using D's compile time function evaluation
import std.algorithm;
string numerals(){
    auto s = cartesianProduct(["","I","II","III","IV","V","VI","VII","VIII","IX"],
                              ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"],
                              ["","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"],
                              ["","M","MM","MMM"]);
    s.popFront();//skip first
    char[] result="enum ";
    int i=1;
    foreach(p;s){
        result~=p[3]~p[2]~p[1]~p[0]~"="~i++~",";
    }
    result[$-1]=';';//replace last , with a ;
    return result.idup;
}
mixin(numerals());

J - 78 char
This only goes up to MMMCMXCIX = 3999, as with the other solutions.
(}.,;L:1{M`CDM`XLC`IVX('';&;:(_1,~3#.inv]){' ',[)&.>841,3#79bc5yuukh)=:}.i.4e3

Breaking it down (recall J is usually read from right to left, unless superseded by parentheses):

M`CDM`XLC`IVX - Four boxes of letters. We're going to use numeric arrays into index into these letters and build up subwords of Roman numerals.
841,3#79bc5yuukh - This is the numeric data, tightly encoded.*
(_1,~3#.inv]) - This will decode the above data, by expanding in ternary and appending -1.
('';&;:(...){' ',[)&.> - Pairing up the numbers on the left with the boxes on the right (&.>), decode the arrays of numbers and use them to index into the letters. We treat 0 as space by prepending a space character to the letter lists. This procedure builds lists of words like I II III IV V VI VII VIII IX and M MM MMM.
{ - Take the Cartesian product of these four boxes full of words. Now we have a 4D array of all the Roman numerals.
}.,;L:1 - Run all that into a single 1D list of Roman numerals, and remove the empty string at the front because it would create an error. (L: is a rare sight in J golf! Usually there are not this many levels of boxing involved.)
}.i.4e3 - The integers from 0 to 4000, excluding the endpoints.
Finally, we put everything together with a global assignment =:. J allows you to have a boxed list of names on the LHS, as a form of computed multiple assignment, so this works out fine.

Now the J namespace is full of variables representing Roman numerals.
   XCIX
99
   MMCDLXXVIII
2478
   V * LXIII   NB. 5*63
315
   #4!:1]0     NB. How many variables are now defined in the J namespace?
3999

* I need the number 2933774030998 to later be read in base 3. It so happens that I can express it in base 79 using digits no greater than 30, which is good because J can only understand digits up to 35 (0-9 and then a-z). This saves 3 characters over decimal.

Haskell, using meta-programming in Template Haskell and roman-numerals:
{-# LANGUAGE TemplateHaskell #-}
import Data.Char (toLower)
import Language.Haskell.TH
import Text.Numeral.Roman

$( mapM (\n -> funD (mkName . map toLower . toRoman $ n)
                    [ clause [] (normalB [| n |]) []]) $ [1..1000 :: Int] )

main = print xlii

Haskell reserves identifiers starting with upper case letters for constructors, so I used lower-case.

Python
The Idea is simple as the other answers. But Just to be neat and not to pollute the global namespace, a context manager is used. This also imposes the restriction, that you need to declare before hand, the extent of Roman numerical you are planning to use.
Note Just to keep it simple, and not to reinvent the wheel, I have utilized the Roman python package
Implementation
class Roman(object):
    memo = [0]
    def __init__(self, hi):
        import rome
        if hi <= len(RomanNumericals.memo):
            self.romans = Roman.memo[0:hi]
        else:
            Roman.memo += [str(rome.Roman(i))
                    for i in range(len(Roman.memo),
                            hi+1)]
            self.romans = Roman.memo
    def __enter__(self):
        from copy import copy
        self.saved_globals = copy(globals())
        globals().update((v,k) for k,v in enumerate(self.romans[1:], 1))
    def __exit__(self,*args ):
        globals().clear()
        globals().update(self.saved_globals)

Demo
with Roman(5):
    with Roman(10):
        print X
    print V
    print X

10
5

Traceback (most recent call last):
  File "<pyshell#311>", line 5, in <module>
    print X
NameError: name 'X' is not defined

Rebol
Rebol []

roman-dialect: func [
    {Dialect which allows Roman numerals as numbers (integer!)}
    block [block!]
    /local word w m1 m2 when-in-rome rule word-rule block-rule
  ][
    when-in-rome: does [
        if roman? w: to-string word [change/part m1 roman-to-integer w m2]
    ]

    word-rule:  [m1: copy word word! m2: (when-in-rome)]
    block-rule: [m1: any-block! (parse m1/1 rule)]
    rule:       [any [block-rule | word-rule | skip]]

    parse block rule
    do block
]

; couple of helper functions used in above parse rules

roman-to-integer: func [roman /local r eval] [
    r: [IV 4 IX 9 XL 40 XC 90 CD 400 CM 900 I 1 V 5 X 10 L 50 C 100 D 500 M 1000]
    eval: join "0" copy roman
    foreach [k v] r [replace/all eval k join " + " v]
    do replace/all to-block eval '+ '+
]

roman?: func [s /local roman-chars] [
    roman-char: charset "IVXLCDM"
    parse/case s [some roman-char]
]

Example
roman-dialect [
    m: X + V
    print m
    print M + m  ; doesn't confuse the variable m with Roman Numeral M
    if now/year = MMXIV [print "Yes it is 2014"]
    for n I V I [
        print [rejoin [n "+" X "="] n + X]
    ]
]

Output:

15
1015
Yes it is 2014
1+10= 11
2+10= 12
3+10= 13
4+10= 14
5+10= 15

Disclaimer: I'm sure there are other (and probably better!) ways of doing this in Rebol as well.
PS. My roman-to-integer function is a transliteration of histocrat's nice Ruby algorithm for converting Roman Numeral string into a number.  Returned with thanks! +1

Python
This is possibly the simplest solution using Python:
ns = [1000,900,500,400,100,90,50,40,10,9,5,4,1]
ls = 'M CM D CD C XC L XL X IX V IV I'.split()
for N in range(1, 4000):
    r=''
    p=N
    for n,l in zip(ns,ls):
        while p>=n:
            r+=l
            p-=n
    exec('%s=%d'%(r,N))

i, j = XIX, MCXIV
print i, j

Better to use globals()[var] = value than exec().

APL (Dyalog APL), 77 bytes
Prompts for Roman numeral maximum length and defines all variables.
t←'IVXLCDM',⊂⍬
{⍎⍕⍵'←',+/2(⊣×¯1*<)/0,⍨(∊1 5∘×¨10*⍳4)[t⍳⍵]}¨,/t[⍉8⊥⍣¯1⍳¯1+8*⎕]

t← t gets
'IVXLCDM', Roman chars followed by
⊂ an enclosed
⍬ empty list
t[…] index t with…
 ⍉ the transposed (to get the right order)
 8⊥⍣¯1 appropriate width base-eight representation of
 ⍳ the first n indices, where n is
 ¯1+ one less than
 8*⎕ eight to the power of numeric input
,/ flatten rows (each representation)
{…}¨ apply the following anonymous function on each representation…
 (…)[t⍳⍵] corresponding to the positions of the argument's items in t, select from…
  ∊ the enlisted
  1 5∘×¨ one and five times each of
  10* ten to the power of
  ⍳4 zero through three
 0,⍨ append zero
 2(…)/ on each length-two sliding window, apply the following anonymous function train…
  ⊣× the left argument times
  ¯1* negative one to the power of
  < whether the left argument is less than the right argument
 +/ sum
 ⍵'←', prepend the argument (the Roman numeral) and an assignment arrow
 ⍕ format (to flatten and convert the number to text)
 ⍎ execute that (makes the assignment outside the anonymous function)
Try it online! (using max-length 5)

PHP
There a several rules for valid roman numbers

Write the greatest value befor the lower values
Subtract only [I,X,C] before the next 2 greater values
Subtract double [I,X,C] before the next 2 greater values
Subtract double [I,X,C] before the greater values
Combine 4+5

Online Version
Step 1 Create the rules
{"M":1000,"IM":999,"IIM":998,"XM":990,"XXM":980,"CM":900,"CCM":800,"D":500,"ID":499,"IID":498,"XD":490,"XXD":480,"CD":400,"C":100,"IC":99,"IIC":98,"XC":90,"XXC":80,"L":50,"IL":49,"IIL":48,"XL":40,"X":10,"IX":9,"IIX":8,"V":5,"IV":4,"I":1}

is the JSON output for all valid roman numbers
$rule_sub_all=$rule_add=$rule_sub_simple=["M"=>1000,"D"=>500,"C"=>100,"L"=>50,"X"=>10,"V"=>5,"I"=>1];
foreach(["I","X","C"]as$roman_letter){
    $rule_sub_simple[$roman_letter.array_search($value=$rule_add[$roman_letter]*5,$rule_add)]=$value-$rule_add[$roman_letter];
    $rule_sub_simple[$roman_letter.array_search($value=$rule_add[$roman_letter]*10,$rule_add)]=$value-$rule_add[$roman_letter];
}
$rule_sub_lower_one=$rule_sub_double=$rule_sub_simple;
foreach(["I","X","C"]as$roman_letter){
    $rule_sub_double[$roman_letter.$roman_letter.array_search($value=$rule_add[$roman_letter]*10,$rule_add)]=$value-2*$rule_add[$roman_letter];

foreach($rule_add as$key=>$value){
    if($value>$rule_add[$roman_letter])$rule_sub_all[$roman_letter.$key]=$value-$rule_add[$roman_letter];
    if($value>5*$rule_add[$roman_letter])$rule_sub_all[$roman_letter.$roman_letter.$key]=$value-2*$rule_add[$roman_letter];
    if($value>10*$rule_add[$roman_letter])$rule_sub_lower_one[$roman_letter.$key]=$value-$rule_add[$roman_letter];
    }
}
arsort($rule_sub_all);
arsort($rule_sub_lower_one);
arsort($rule_sub_double);
arsort($rule_sub_simple);

Step 2 Make lists for all rules till 3999
$array_sub_lower_one=$array_sub_double=$array_sub_all=$array_add=$array_sub_simple=[];
for($i=1;$i<4000;$i++){
    $number_sub_all=$number_add=$number_sub_simple=$number_sub_double=$number_sub_lower_one=$i;
    $roman_letter_sub_all=$roman_letter_add=$roman_letter_sub_simple=$roman_letter_sub_double=$roman_letter_sub_lower_one="";
    foreach($rule_sub_all as$key=>$value){
        $roman_letter_sub_all.=str_repeat($key,$d=$number_sub_all/$value^0);$number_sub_all-=$value*$d;
        if(in_array($value,$rule_sub_lower_one)){
        $roman_letter_sub_lower_one.=str_repeat($key,$d=$number_sub_lower_one/$value^0);$number_sub_lower_one-=$value*$d;}
        if(in_array($value,$rule_add)){
        $roman_letter_add.=str_repeat($key,$d=$number_add/$value^0);$number_add-=$value*$d;}
        if(in_array($value,$rule_sub_simple)){
        $roman_letter_sub_simple.=str_repeat($key,$d=$number_sub_simple/$value^0);$number_sub_simple-=$value*$d;}
        if(in_array($value,$rule_sub_double)){
        $roman_letter_sub_double.=str_repeat($key,$d=$number_sub_double/$value^0);$number_sub_double-=$value*$d;}
     }
    $array_sub_lower_one[$roman_letter_sub_lower_one]=$i;
    $array_sub_all[$roman_letter_sub_all]=$i;
    $array_add[$roman_letter_add]=$i;
    $array_sub_simple[$roman_letter_sub_simple]=$i;
    $array_sub_double[$roman_letter_sub_double]=$i;
}

Step 3 Create constants
Combine all lists and define constants
foreach(array_merge($array_add,$array_sub_simple,$array_sub_lower_one,$array_sub_double,$array_sub_all)as$key=>$value){ define($key,$value); }

Output
In the example mutiply two valid versions of the number 8
echo IIX *  VIII;

Nice, but how do I use this? I'm not fluent in PHP; Could you please give an example of how this enables me to write Roman numerals in the code?

@Daniero Now the code should work

Ah, that's better :)

Lua
local g={}
setmetatable(_G,g)
local romans = {I = 1,
                V = 5,
                X = 10,
                L = 50,
                C = 100,
                D = 500,
                M = 1000}
local larger = {    -- Precalced, for faster computing.
                I = "VXLCDM",
                V = "XLCDM",
                X = "LCDM",
                L = "CDM",
                C = "DM",
                D = "M",
                M = " " -- A space will never be found, and it prevents the pattern matcher from erroring.
}
local storedRomans = {}
function g:__index(key)
    if storedRomans[key] then
        return storedRomans[key]
    end
    if key:match"^[IVXLCDM]+$" then
        local n = 0
        local i = 1
        for s in key:gmatch"." do
            local N = romans[s]
            if key:find('['..larger[s]..']',i) then
                n = n - N
            else
                n = n + N
            end
            i = i + 1
        end
        storedRomans[key] = n
        return n
    end
end

This effects the metatable of the global table, giving it a new index function. When a global variable which only contains roman numerals is asked for, eg XVII, it parses it.
Easy to test;
print(XVII) -- 42
print(VI)   -- 6
print(III)  -- 3
print(MMM)  -- 3000

Try it online!

Excel VBA, 204 183 bytes
A subroutine which takes no input, and when run, creates Enum R, which contains all of the Roman Numeral values. These values may be used directly, without referencing the Enum.
Requires programmatic access to the VBE Project module.
Enum hold values from 1 to 3999.
Note: Terminal "s on lines 7, 8, and 13 are included for syntax highlighting only, and do not contribute to the bytecount
Global c
Sub a(s)
c.AddFromString s
End Sub
Sub b
Set c=ThisWorkbook.VBProject.VBComponents.Add(1).CodeModule
a"Enum R"
a"I=1"
For n=2To 3999
[A1]=n
a[Roman(A1)]
Next
a"End Enum"
End Sub

Ungolfed and Explained
Global C As CodeModule                                              '' dim object to hold module to be added

Private Sub pWriteLine(ByRef s As String)                           '' define a helper sub that writes a single
    C.AddFromString s                                               ''   line containing string `s` to global
End Sub                                                             ''   codemodule `c`

Public Sub InitializeRomanNumerals()
    Set C = ThisWorkbook.VBProject.VBComponents.Add(1).CodeModule   '' Create Module
    Call pWriteLine("Public Enum RomanNumeral")                     '' Write Enum Header
    Call pWriteLine("I = 1")                                        '' Write First line, and set value to 1
    For n = 2 To 3999                                               '' iter from 2 to 3999
        [A1] = n                                                    '' push value to A1
        Call pWriteLine([Roman(A1)])                                '' write a line containing roman numeral value of A1,
                                                                    ''  enum value will auto increment to be 1 over
                                                                    ''  that of the line above
    Next n                                                          ''
    Call pWriteLine("End Enum")                                     '' Write Enum Footer
End Sub

JavaScript, 167 bytes
f=n=>n<4e3?"M1000CM900D500CD400C100XC90L50XL40X10IX9V5IV4I1".replace(/(\D+)(\d+)/g,(_,r,d)=>r.repeat(n/d,n%=d)):`(${f(n/1e3)})`+f(n%1e3)
for(i=0;i<4e3;i++)this[f(i)]=i

The Decimal to Roman function comes from this answer (thanks Neil !)
Then it will add all of them to the root object (this). Very optimized, and definitively a good practice I know !
Just paste it to the browser's console to try it out !

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
It's a rainy day
Context

It's Valentines Day. The only one you ever loved left you yesterday
  for this guy she always found "stupid and uninteresting". On your
  way home, you've been stuck in traffic, listening to old songs on the
  radio, the rain hitting the windscreen is rocking you. After a while
  in your car, you find yourself alone in your small apartment being
  unable to think of something else but her. There is no light and you
  stare trough the window, letting darkness surrounds you. There is no
  one to talk to, your friends are now gone a long time ago after
  warning you about this new girl haunting your mind. You start up your
  computer, as it's the only thing you can do, open your browser and
  post a new programming puzzle to stackexchange, in an attempt to change your mind.

Challenge
Write a program in the language of your choice simulating the rain which falls on the ground. The output can be composed of ASCII characters or 2D/3D rendered. The camera is fixed : you are above looking straight to the ground. Your program must includes some kind of animation like refreshing the console or the page each time you generate a new "frame". It has to be realistic, I know it's a bit subjective but let's say you can't just fill all the ground in only one big drop.
The output don't have to be an image but if you're using cryptic language it's better to provide a .gif to illustrate how it looks in action (but of course, it will not affect your score if you don't).
Rules

Your score is the total of bytes used
-20 points if you use colours
-50 if you achieve to render some kind of wind
Lowest score wins

Example
A very basic example of what should be rendered:

I hope you'll do better and enjoy this challenge.
Sorry for my english, feel free to edit my post if you want to correct some errors
Leader board
If your name is not listed it's because your attempt has been considered not fitting the rules.
Tobia - APL - 35
j6m8 - Processing.js - 38
The Guy with The Hat - Processing - 42
ace - Processing - 74
kelunik - JS/CSS - 89
Riot - Bash - 91
Michael - JS/jQuery - 105
Florent - HTML/JS - 123
David Carraher - Mathematica - 134
Doorknob - HTML/JS - 150
undergroundmonorail - Python - 175

Congratulations to Tobia !

I sincerely hope the first paragraph isn't a true story.

@KendallFrey Indeed.

"you are above looking straight to the ground."??

@DavidCarraher yes, like you're in the sky looking at the floor.

How does wind affect what rain falling on the ground looks like? IMO no-one would be able to get those 50 points as the requirement doesn't make sense. But I don't spend a lot of time looking at the ground outside in the rain, so perhaps I'm missing something.

@Dukeling, If you manage to add scaling on drops, you can easily add a wind effect.

@BenH Assuming that the patch of ground you are looking for, is surrounded by other ground, then the wind that would blow rain to the right, would also blow wind from off frame, into frame.

I don't think this should be code-golf as there's too much leniency on the potential outputs

The first paragraph along with the camera position for this rendering is quite macabre.

"stupid and uninteresting"

Imagemagick sounds horrifying. I tried to fix that gif in GIMP, but there were 115 frames, so I gave up D:

@BenH I've updated your image; your frames were out of order. Most likely because you exported them as img1, img2, img3 ... instead of img001, img002, img003 ...

@primo oh thank you, I did not think of that.

Can I reuse my own answer https://codegolf.stackexchange.com/a/143018/29325 ?

APL, 105 chars/bytes* – 20 – 50 = 35 score
e←{⍞←∊'␛['⍵}
e¨'36m' '?25l' '2J'
{⍵←3⌊⍵+3×0=?t⍴50
⍵{(⍵c)←⍕¨⍵+1
e⍵';'c'H',' .∘⍟'[⍺]}¨⍳t
∇0⌈⍵-1}0⍴⍨t←24 80

*: Most APL implementations support some form of (legacy) single-byte charset, that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of golfing, a program that only uses ASCII characters and APL symbols can be scored as chars = bytes.
I tested it on Nick's latest apl.js on Node.js in an OS X terminal. But I haven't used anything specific to his dialect, so it should work on any modern APL that can be run on an ANSI terminal and supports d-funs {...}, strand assignment (a b)←..., and commute ⍨, such as Dyalog for Linux or for Raspberry PI (with ⎕IO←0)
The ␛ in line 1 is a literal escape character (which is 1 byte). You can input it using Ctrl-V Esc in a Linux terminal or in Vim, or supposedly something like Alt-027 in Windows. Also, I couldn't find a reliable way to discover the terminal size, so you might want to edit the number of rows and columns at the end of the last line.
I defend the 50 bonus by the fact that each raindrop goes through the following shapes: ⍟∘. which give the impression of a slight downwards wind, given that the scene is being looked at from above. In fact, looking at the gif below, you should get the impression that each drop is gently moving downwards and to the left, before disappearing on the ground.
Ungolfed version:
e←{⍞←∊"␛["⍵}                  # utility to print escape sequence
e¨'36m' '?25l' '2J'            # set cyan, hide the cursor and clear screen
{                              # repeat (⍵=current board of raindrops)
  ⍵←3⌊⍵+3×0=?t⍴50              #   add some new drops (=3) in random places
  ⍵{                           #   print the drops (⍺=drop value, ⍵=coords)
    (r c)←⍕¨⍵+1                #     convert the coordinates to string
    e r';'c'H',' .∘⍟'[⍺]       #     print or clear the drop
  }¨⍳t                         #   ..
  ∇0⌈⍵-1                       #   remove 1 from every drop and repeat
}0⍴⍨t←24 80                    # ..starting with an empty board

Output:

APL, different style
Out of competition.
m←×/t←1+(ζη)←2×(βγ)←24 80
e←{⍞←∊(⎕UCS 27)'['⍵}
s←{⍵[β-1-⍳β;1+⍳γ]}
p←{⍺{e'H'⍺,⍨{⍺,';',⍵}/⍕¨⍵}¨(,s⍵)/,1+⍳βγ}
e¨'2J' '36m' '?25l'
{'/'p⍵←(200<m÷?t⍴m)∨0⍪⍵[⍳ζ;1+⍳η],0
' 'p(~⍵)∧0,⍵[1+⍳ζ;⍳η]⍪0
'.∘°'[?(+/,sδ)/3]pδ←⍵∧~d←.2<m÷⍨?t⍴m
∇⍵∧d}t⍴0

Here my aim was to give the impression of raindrops falling with a slant and accumulating on the ground, while trying to keep the number of visible drops (either falling or splattered) constant on average. The trick was to create a number of new falling drops / at every cycle and having the falling drops "wipe out" any splattered ones they travel across.
The result is strangely reminiscent of the Matrix code.
Output
(the jerk every 5s is the gif looping)

This is nice, but I don't think the ESC character is being printed right. http://i.stack.imgur.com/vLERQ.png I tried pasting the code with gedit too, didn't work.

You got your score wrong. The question says "bytes", not "chars".

@Riking I edited that part. If you try it again it should work.

@Tobia Show me a picture of you sitting at your IBM 5100, and I'll buy the chars = bytes argument.

@primo http://imageshack.com/a/img811/314/86dt.jpg

@Tobia I concede the point ;)

Bash: 111 bytes - 20 = 91 points!
A contemplative gentle drizzle in your terminal.  Adjust the numbers 819 and 41 for different height and width respectively.
e='printf \e';while :;do for i in {0..819};do((RANDOM<9))&&$e[1\;36m.||$e[1C;((i%41<1))&&$e'
';done;$e[20A;done

A pleasant bonus is the way the cursor pitter-patters across the rain area.
Edit: shortening from 140 bytes to 129 bytes thanks to @manatwork's suggestions.
2nd edit: shortening from 129 bytes to 111 bytes thanks to @manatwork's and @Tobia's suggestions, plus additional inspiration - see comments.
(Note: screenshot shows previous less-golfed version of the code, which is functionally identical)

You can spare: 2 characters by joining echo's options; 2 characters by using \e instead of \033; 3 characters by using : instead of true; 5 characters by using arithmetic evaluation (((…))): e='echo -ne \e';while :;do for i in {0..19};do for i in {0..40};do ((RANDOM<9))&&$e"[1;36m".||$e[1C;done;$e' ';done;$e[20A;done.

@manatwork: all excellent suggestions, can't believe i missed combining echo's options!  Thanks!

You not need the sigil inside arithmetic evaluation. And there must be a trailing newline at the end of your code. Should be only 127 characters.

I believe what @manatwork means is that you don't need to use the dollar sign inside double parentheses: ((RANDOM<9)) works just as well. Also, you could try shrinking your code by combining the two for {0..19} and {0..40} into a single for {0..819}, using something like $((i%41)) inside it.

Not to mention, this [1\;36m is one char less than this "[1;36m" and you can probably take out the space before ((.

Someone stop me!! e='printf \e' is 2 char shorter than e='echo -ne \e'!

Hide that cursor with \e[?25l

And trim another char by using $e[C

@Tobia - thanks for the suggestion, it wasn't quite that simple but i used ((i%41<1))&& instead.  $e[C doesn't work correctly for me... Michael - i'd hide the cursor but it would a) lower my score and b) look less pretty :)

After running this, your terminal will be set to bold blue text. Fix that by running $e[0m.

Or just reset.  That only happens if your prompt has no colour control characters in it.

Python, 312 bytes - 50 (wind) = 262
from pygame import*
R=__import__('random').randint
t,u=640,480;init();d=display;s=d.set_mode((t,u))
w=[255]*3;r=range(t)
a=[[R(0,t),R(0,u),R(3,6)]for i in r]
while time.wait(9):
 d.flip();event.get();s.fill(R(0,99)<1and w)
 for i in r:x,y,z=a[i];draw.line(s,w,(x,y),(x+z,y+2*z));a[i][0]=(x+z)%t;a[i][1]=(y+z*2)%u

Sample output (a 50-frame loop):

Actual playpack is significantly faster than gifs allow.

You could do w=(0,0,255) instead of w=[255]*3 and get -20 points

@ChristianCareaga I could, but I think white looks better.

Only problem in my eyes: You're viewing the rain from the side, while the rules state a fixed camera looking straight down.

@JohannesH. Or, it's a very, very windy day.

@primo: Given the long distance but slow speed, it's more like slightly windy but a very, very hight tower you're at :D

Oh, plus a camera with very bad FPS and long duration of exposure, as each drop is quite long (but moving to slow for strong wind). I think we got that covered now ^^

@JohannesH. "Actual playpack is significantly faster than gifs allow." By significant, I mean approximately 7 times faster.

Nice one, but it's a side view. It's precised in the description that your program must simulates rain hitting the ground.

@primo General way to fix this is remove all but every 7th frame, and use a 7x longer sample

I like the occasional flashes of lightning! :P

-1: Not an answer to this question

@ace I claim that this is a top view, with very high wind, and that the droplets are indeed falling towards the ground. I fail to see how this doesn't meet the specification.

@primo maybe because the droplets never reach ground, and no height difference can be perceived?

@ace there are in fact four different depths. If you don't like the submission, you don't need to upvote it.

One character gets saved by using R=__import__("random").randint instead of the from random... line.

HTML / JS, 170 chars - 20 = 150 points

<canvas id=c></canvas><script>d=400;with(c)width=height=d,t=getContext('2d');t.fillStyle='blue';setInterval("t.fillRect(Math.random()*d,Math.random()*d,5,5)",50)</script>

(sidenote: golfed further by passing a string to setInterval, with, automatic ID variable names... it feels so wrong! shudders)
It just draws random blue rectangles.
HTML / JS, 309 chars - 20 - 50 = 239 points
Now with wind!

<canvas id=c></canvas><script>s=400;r=Math.random;with(c)width=height=s,t=getContext('2d');t.fillStyle='blue';o=[];setInterval("t.clearRect(0,0,s,s);for(i=0;++i<o.length;)d=o[i],t.fillRect(d[0],d[1],d[2],d[2]),d[0]+=1,d[1]+=2,d[2]-=1,d[2]<0?o.splice(i,1):0;if(r()<.6)o.push([r()*400,r()*400,20])",50)</script>

163 bytes: <canvas id=c /><script>d=400;with(c)width=height=d,t=getContext('2d');t.fillStyle='blue';setInterval("t.fillRect(Math.random()*d,Math.random()*d,5,5)",50)</script> AAAHHH! I used with! I feel dirtier than passing a string to setInterval :p

@NiettheDarkAbsol Thanks ;) It seems that (on Chrome at least) canvas can't auto-close, but other than that that works perfectly! (Also, using automatic ID variable names feels so dirty as well :D)

Some browsers seem more lenient in that area... But it avoids having to use onload. I must say I like @Florent's way of avoiding the duplicate Math.random()

@Doorknob canvas autoclose in Chrome! My answer was developed/tested in this browser.

I'm not sure I get the wind version

If they were round instead of square and you managed to create a splash after each one disappears (i.e. another circle that grows and shrinks rapidly) the second one would be amazing.

Trimming those bytes.... 301-20-50=231 points!

Upvote for the second one, with the drips sinking into the ground/puddle.

@Doorknob Save 6 bytes: r=Math.random;t.fillRect(r()*d,r()*d,5,5)

JS + jQuery (172-20-50 = 102)
Copy/Paste that line in the browser console (generally press F12 key) :
r=Math.random;w=$(window);setInterval("$('<b>♥</b>').css({color:'red',position:'fixed',top:r()*w.height(),left:r()*w.width()}).appendTo('body').animate({fontSize:0},3e3)",9)

Animated red hearts rain for Valentine's day !

I'm on firefox right now and when I paste your code in the console, there is a single hearth falling at the speed of light and that's all. Also don't forget that the rain must hit the ground and not just fall down.

@BenH, should work now... at the cost of 3 more bytes.

it works now, thanks for the correction. But does not qualify until you swap your point of view. Also I can't really see the wind effect because hearts are falling too fast.

Ohhh missed the point "you are above looking straight to the ground" !

@BenH, does it satisfy the conditions now ?

well, it's not realistic. Hearts are coming from the top of the screen and stick to random positions of the page. That does not really match the point of view condition.

Well, a hearts rain is not realistic ! :) Anyway, I've changed the animation, let me now if it's better for you.

I was about to tell you about scaling. It's neat but reversed, if you're in the sky and looking to the ground, hearts shrink as they fall. :)  I think you should also slow down the animation a bit and work on the wind effect because for now I can't see it. You're in the right way !

This is very similar to effect used on this site: 2-ch.so/b/ (appears only today)

AUGGGGHH! How do I stop it?!

@TheGuywithTheHat Just close the tab.

@user2509848 But is there any other way?

Also it should be byte count, so in case you're using UTF-8 the heart counts as three bytes.

@TheGuywithTheHat: Check out the answer to http://stackoverflow.com/questions/6843201/how-to-clearinterval-with-unknown-id.

@TheGuywithTheHat, reload the page

Brilliant! I think this captures the heart of the question.

@andrewb that was punny

Mathematica
134 - 20 = 114
2D
n = 99; m = Array[0 &, {n, n}]; r := RandomInteger[{1, n}, {2}]
Table[ArrayPlot[m = ReplacePart[m, r ->  1], ColorRules -> {1 -> Blue}], {k, 250}];
Export["d.gif", d]

3D
The raindrop shape is made via a revolution plot around the z axis.
Initially, rain is generated for a region that extends well above the display region. The appearance of falling rain is achieved by shifting the Viewpoint upwards along the z-axis. (It is more efficient than recalculating the position of each raindrop.)

r = RandomInteger; z = Table[{r@30, r@30, r@160}, {100}];
w = RevolutionPlot3D[{.7 Sin[x] Cos[x], 0,   1.4 Sin[x] }, {x, 0, -Pi/2},
PerformanceGoal -> "Speed"][[1]];
c = Map[Translate[w, #] &, z];
p = Table[Graphics3D[c, PlotRange -> {k, k + 50}], {k, 1, 100}]
Export["p.gif", p]

With Wind
There is considerable overhead to making the rain fall with wind.  But I'm including here anyway.
The blue floor pretty much keeps {x,y} view region confined to the area of interest.
There are some glitches, but, oh well,
r = RandomInteger;
z = Table[{r@120, r@30, r@180}, {800}];
w = RevolutionPlot3D[{.7 Sin[x] Cos[x], 0,   1.4 Sin[x] }, {x,
     0, -Pi/2}, PerformanceGoal -> "Speed"][[1]];
c = Map[Translate[w, #] &, z];
g[k_, z1_, w_, c1_] :=
 Module[{z2},
  z2 = Cases[z, {x_, _, _} /; 0 + k < x < 30 + k];
  c = Map[Translate[w, #] &, z2];
  Graphics3D[{Polygon[{{0 + k, 0, 1 + k}, {30 + k, 0, 1 + k}, {30 + k,
        30, 1 + k}, {0 + k, 30, 1 + k}}], c},
   PlotRange -> {k, k + 50}]]

p = Table[g[k, z, w, c], {k, 1, 100, 1}];
Export["p.gif", p]

From Directly Above
The closest raindrops are clipped but I'll overlook that.

m=40;
r=RandomInteger;
positions=Table[{r@m,r@m,r@1000},{800}];
g[lowZ_,pos_]:=
Module[{hiZ=lowZ+103},
Graphics3D[{PointSize[Small],White,Point[{{0,0,lowZ},{0,m,lowZ},{m,0,lowZ},{m,m,lowZ},{0,0,hiZ},{0,m,hiZ},{m,0,hiZ},{m,m,hiZ}}],
ImageSize-> 350,Sphere/@Cases[pos,{_,_,z1_}/;lowZ<z1<hiZ-2]},PlotRange->{lowZ,hiZ},
ViewPoint-> {0,0,1},ImagePadding->5]]

Shift it to the side in under 50 characters and you lower your score. :)

I love this one

+1 for the last one, with the correct camera angle BUT you forgot that the camera blocks some of the rain.... ;)

@GreenAsJade, The clipping for the 3D (from above) viewpoint is now fixed.

Sweet, but I was being more frivolous than you thought.   I was meaning that there is a physical camera looking down at this, so it should be blocking some of the raindrops :%)

HTML / JavaScript, 156 123 (143 - 20)

<body bgcolor=0 onload="t=c.getContext('2d');t.fillStyle='#07d';setInterval('n=Math.random()*4e4;t.fillRect(n%270,n/150,1,1)',1)"><canvas id=c>

Annotated version:
<body bgcolor="#000">
<canvas id="c"></canvas>
<script>
  onload = function() {
    // Retrieve the rendering context
    t=c.getContext('2d');
    // Set rain color
    t.fillStyle='#07d';
    // Render whenever it is possible
    setInterval(function() {
      // Generate a number between 0 and 40,000
      // 40,000 ~= 270 * 150
      n=Math.random()*4e4;
      // Draw a raindrop.
      // Since x and y are not rounded, the raindrop looks blurry!
      t.fillRect(n%270,n/150,1,1)
    }, 1);
  };
</script>
</body>

Smalltalk (Smalltalk/X)
with random wind ;-)
|BG CLR N1 H W v WIND drops gen newDrops draw remove move buffer|

BG := Color black.
CLR := Color blue lightened.
H := 100.
W := 100.
N1 := 10.
WIND := 0.
drops := OrderedCollection new.

gen := [:n | ((1 to:n) collect:[:i | Random nextIntegerBetween:1 and:W] as:Set) collect:[:x | x@0]].
newDrops := [drops addAll:(gen value:N1)].
draw := [buffer fill:BG; paint:CLR. drops do:[:d | buffer displayPoint:d]].
remove := [drops := drops reject:[:d | d y > H]].
move := [:wind | drops := drops collect:[:d| (d x + wind)\\W @ (d y + 1)]].
v := View new openAndWait.
buffer := Form extent:(v extent) depth:24 onDevice:v device.

[
    [v shown] whileTrue:[
        draw value.
        v displayForm:buffer.
        move value:WIND.
        remove value.
        newDrops value.
        WIND := (WIND+(Random nextBetween:-1 and:1)) clampBetween:-5 and:5.
        Delay waitForSeconds:0.1.
    ]
] fork.

output in view:

It does not qualify since it's a side view of the rain falling, and not the rain hitting the ground. Still a nice wind effect.

Processing, 94 - 20 = 74
void setup(){background(0);fill(0,0,255);}
void draw(){ellipse(random(0,99),random(0,99),3,3);}

(New line added for readability.)
Click here for an online demo.

Processing is really good for problems like these.

Cannot view it in Firefox, default security settings block the Java applet and it doesn't tell me how to override. AFAIK there is a Processing.js port to JavaScript, if you could convert it to JS and post a link I'd be thankful.

@marczellm I'm using Firefox 27.0 on Ubuntu and it works fine. Are you sure there are no prompts asking you whether to allow or block the plugin? I will take a look at a JS version as well.

@ace After I tell all promps to "allow", a security message still blocks it. Thanks for the JS version.

@marczellm added the javascript version into the answer, enjoy :) and just a blind guess, maybe your current java plugin version is outdated and has known security issues

Bash
while true;do echo " / / / / /";echo "/ / / / / ";done

I'm not sure this should be a code golf because there isn't a strict requirement on what the "rain" must look like.
EDIT:
If you want it to look like the camera is pointing straight down use this:
while true;do echo " . . . . .";echo ". . . . . ";done

"The camera is fixed : you are above looking straight to the ground." This appears to be viewing the rain from the side?

Save 9 characters: while echo \ / / / / /;do echo / / / / /;done (or a few more with a recursive function but that'll quickly blow up the stack). @undergroundmonorail Strong wind, diagonal relative to the camera.

@Gilles In that case, we can do while echo -e '\e[0;34m / / / / /';do echo / / / / /;done and get it down to -13 with bonuses :)

that's defintely not looking like rain :D

@Kiwy true that :D

I don't really think this should be considered as an answer.  In short: It's not realistic.  Detailed argument: If I interpreted the question correctly, the rain should fall randomly (or at least pseudo-randomly) and, over a long period of time, the distribution should be similar per unit area. (This is how rain works, right?) However in this answer, it is guaranteed that there will be no rain drops next to any rain drop, so if we take the unit area to be the area of one character, we see that the distribution is uneven.

@ace you're probably right... although the question said nothing about randomness

@professorfish the question did mention "It has to be realistic"

@ace fine, I give up...

Python 2.7: 195 - 20 = 175
I'm sure there's more that can be done here, but this is what I've got for now:
import os,time
from random import*
l=[i[:]for i in[[' ']*100]*50]
while 1:
 os.system('clear')
 l[randint(0,49)][randint(0,99)]='.'
 print'\033[94m\n'.join(''.join(r)for r in l)
 time.sleep(.05)

I'll post a gif of the output when I remember how to do that.
This works on linux. Replacing 'clear' with 'cls' makes it work on windows, but then ANSI colours don't work and I lose the bonus.
I have a 2D array of one-character strings, initialized to . Every 0.05 seconds, one of them is chosen at random set to ., and the screen is redrawn.
from random import* saves two characters over import os,time,random and using random.randint() twice, though I'm not convinced that's the best way to choose a cell anyway. I wanted to use random.choice() but I couldn't think of a way around immutable strings that wouldn't waste more characters than it saved.

l=[i[:]for i in[[' ']*100]*50], as per http://stackoverflow.com/a/6688361/1114687. 198 - 20 = 178

Oh, wow, I've never seen that before. If I'm reading it correctly, the slice notation does nothing except ensure that it's a unique list and not another reference to the same one, correct? That's really cool! Thank you!

I originally tried l=[[' ']*100]*50, but that just creates 50 references to the same 100-element list, so I searched for the shortest possible way to circumvent that and found the Stack Overflow answer linked above.

132 + 27 - 20 - 50 = 89
Javascript (132)
r=Math.random;setInterval("$('body').append($('<i>∘</i>').css({left:r()*2e3,top:r()*2e3}).animate({left:'+=70',fontSize:0},500))",1)

CSS (27)
i{color:blue;position:fixed

Demo: http://jsfiddle.net/kelunik/5WC87/4/embedded/result/

It's from side view, it does not qualify for the moment.

@BenH You're right, missed that point, new version is in my answer now.

seems like nothing happens when trying your code in firefox console :/

@BenH That's why there's a jsfiddle-demo.

Processing, 62 - 20 = 42
void draw(){stroke(0,0,214);point(random(0,99),random(0,99));}

Generates blue pixels on a white background. Demonstration in a very similar language here: https://www.khanacademy.org/cs/rain2/6172053633761280

Obligatory +1 for extreme terseness.

Processing.js, 86 - 20 = 66
...but it also slowly fades out (the ground absorbs the rain, naturally). Points for that?
g=99;r=random;void draw(){fill(0,9);rect(0,0,g,g);fill(0,g,r(g));rect(r(g),r(g),2,2);}

Bonus features include varying between greenish and blueish (it's clearly dirty 'city' rain).
Also, I was very pleased that I got to use a JavaScript hack in here; Note that, because this is processing.js, you can throw in things like the typeless declaration of g=99, or the alias of r for random (cross-language alias!).
Any other ideas to minify?
Readable version:
g = 99;
r = random;                  // Javascript trickery
void draw() {
    fill(0, 9);
    rect(0, 0, g, g);        // Fade the background
    fill(0, r(g), r);
    rect(r(g), r(g), 2, 2);  // Add a new drop
}

The whole thing can be viewed here.
...plus another version without fade: 58 - 20 = 38
If you don't like fading and don't mind grey dirt:
r=random;void draw(){fill(0,0,255);rect(r(99),r(99),2,2);}

Tcl/Tk, 139 - 20 = 119
Reusing my own answer http://codegolf.stackexchange.com/a/143018/29325
Must be run in the interactive shell
gri [can .c -w 40 -he 40]
set x 0
wh 1 {.c cr o $x [set y [exp int(rand()*40)]] $x [set x $y] -f #[form %06x [exp int(rand()*255**3)]]
upd}

Unfortunately, converting expr int(rand()* into a proc makes the script have one byte more!

To stop, one just needs to click the ineffable "X" button.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Plot gif of 3 dimensional heart in R
inspired by this blog: http://alstatr.blogspot.co.uk/2014/02/r-animating-2d-and-3d-plots.html I made a 2D gif of a heart with:
library(animation)
saveGIF({
for(i in 1:150){
dat<- data.frame(t=seq(0, 2*pi, by=0.1) )
xhrt <- function(t) 16*sin(t)^3
 yhrt <- function(t) 13*cos(t)-5*cos(2*t)-2*cos(3*t)-cos(4*t)
dat$y=yhrt(dat$t)
dat$x=xhrt(dat$t)
with(plot(x,y, type="l", xlim = c(-100  , i ^ 2 / 10 )) )
}
}, interval = 0.1, ani.width = 550, ani.height = 550)

I wonder if anyone out there could show me how to do this in 3D!

pepsimax I added three tags that seem relevant to your question.  Hope that's ok.

@pepsimax You may want to add an objective winning criterion before this questions gets closed because its off-topic.

Btw, if you remove the R tag, so other languages can compete, you may find that more folks take part.

Mathematica
This is done in Mathematica, but it may give you some ideas as to how to implement it in R.
hearts = Table[
  With[{v = RotationTransform[\[Theta], {0, 0, 1}][{3, 0, -.2}]},
   ContourPlot3D[(2 (4/3 x)^2 + 2 y^2 + z^2 - 1)^3 - (4/3 x)^2 z^3/
       10 - y^2 z^3, {x, -2, 2}, {y, -2, 2}, {z, -2, 2},
    MaxRecursion -> 6, Mesh -> None,
    BoxRatios -> {.3, 1, 1},
    SphericalRegion -> True,
    Contours -> {0}, Boxed -> False, PlotRange -> All, Axes -> False,
    ViewPoint :> v, ContourStyle -> Red,
    ImageSize -> 300]], {\[Theta], 0, 2 Pi, Pi/24}]


text:
Print a specific value in the infinite Walsh matrix
The Walsh matrix is an interesting fractal matrix with the property that every single value in a Walsh matrix has a value of either -1 or 1. Additionally, the size of a Walsh matrix is always a power of 2.
Because each Walsh matrix is identical to the top-left quarter of the immediately higher-order Walsh matrix, we can create a generalized "infinite Walsh matrix" by considering the limit of the sequence of Walsh matrices of order N, as N goes to infinity. From here on, we will call this infinite generalization the Walsh matrix.
Your task is to build a program that takes the coordinates of a location in the Walsh matrix and returns the value that occurs there.
Your program will accept two integers x and y as input (in any form you choose), and output the value that appears in the x+1th row of the y+1th column of the Walsh matrix. For example, the input
2 5

will return 1, as the 3rd row in the 6th column of the Walsh matrix has a value of 1. The input
6 4

will return -1, as the 7th row in the 5th column of the Walsh matrix has a value of -1. The input
2834719 394802

will return -1, as the 2384720th row of the 394803rd column has a value of -1.
The shortest code to do this in any language wins.

I quickly figured out a procedure for determining the value of any cell.  Problem is, it only gives the correct answer half of the time. :)

print "0 ± 1"

@DavidCarraher, it seems that if you output 1 you'll do better than 50%.

@Peter Taylor, Great idea, and your solution even saves a few characters.

@PeterTaylor Of course, the limit as you go to infinity is still 50%.

Please add a minimal description of the matrix so that the problem makes sense when wikipedia is down.

GolfScript (18 15 14 bytes)
~&2base-1\0-,?

Takes input space-separated; outputs to stdout. Thanks to Howard for pointing out that the space in the 15-char solution was removable.
The way I reasoned to this solution is quite simple. Take the highest set bit of x|y: this tells you the size of the smallest Walsh matrix which contains the relevant index. Then clearing that bit in both x and y drops us down to the top-left quadrant, and we need to multiply by -1 if we were previously in the bottom-right quadrant: i.e. if the bit was set in both x and y. By induction down the bit sequence, we just need to count the number of bits set in x&y.

Of course it is much shorter to write ~&2base-1\0-,?.

Forth (gforth), 44 bytes
: f and 1e 63 for s>d 2* 1+ s>f f* 2* next ;

Try it online!
The function takes two word-sized unsigned integers (64 bits on TIO). It returns -1 or 1 on the floating-point stack and leaves a garbage 0 on the main stack.
The algorithm follows Blckknght's submission, but the task made me explore LOTS of possibilities for writing Forth programs - from bit shift, divmod, single-to-double conversion to abusing floating-point stack. (The TIO link has several alternative definitions of f which all work, but are longer than the main answer.)
How it works
: f ( u1 u2 -- -1e_or_1e )  \ Takes two integers and returns a float 1 or -1
  and 1e                    \ Bitwise and(=N), then put a 1(=R) on the FP stack
  63 for                    \ Repeat 64 times... (TIO gforth has 64-bit cells)
    s>d                       \ Sign-extend single N to double
                              \ In effect, 0 is pushed if MSB is zero, -1 otherwise
    2* 1+ s>f f*              \ Change 0_or_-1 to 1_or_-1, cast to float and multiply with R
    2*                        \ Shift N left once
  next                      \ End loop
  ;                         \ End function

Python 2 - 42 bytes
print(-1)**bin(input()&input()).count("1")

This takes the two coordinates as separate lines on standard input and writes the answer to standard output.
The algorithm is this:

For coordinates X and Y, find X & Y, the bitwise AND of their values.
Count the number of 1 bits in X & Y. This is the number of times the requested coordinate is in the bottom right quadrant of a level of the matrix.
If the count is odd, the result is -1. If the count is even, the result is 1.

This should work for any positive integer coordinates (including large ones that need more than 32 bits).

x86_64 machine language for Linux, 17 bytes
0x00:  48 21 F7          and    rdi, rsi
0x03:  F3 48 0F B8 C7    popcnt rax, rdi
0x08:  FF C0             inc    eax
0x0a:  24 01             and    al, 1
0x0c:  01 C0             add    eax, eax
0x0e:  FF C8             dec    eax
0x10:  C3                ret

Same algorithm as @Blckknght's answer.
Try it online!

K (ngn/k), 18 16 bytes
-2 bytes by converting to tacit form
-:/[;1]@+/&/+2\,

Try it online!
Based off of @Blckknght's Python 2 answer.

&/+2\, take the (equivalent of) the bitwise-and of x and y
+/ do a popcnt (i.e. number of bits set to 1)
-:/[;1]@ negate 1 that many times and return