The laws would be defined in code written in a programming language. Maybe it would be in two parts, the actual rules and then a library that could run them (like how a form validation library is separate to the actual rules that a developer can write), but that's not important.

Some of the benefits I could see:

  • You could ask it if an action, given certain conditions and involving certain entities, is legal or illegal and what the sentence is. Would we still need lawyers to advise us?
  • When proposing a new law, the program could tell you if it conflicts with an existing law or the situation is already covered by an existing law
  • Automated testing / test driven development could allow loopholes to be minimised and again to minimise conflicts with existing laws
  • The code could be publicly accessible for anyone to examine and test scenarios and potential new laws
  • Comments could be added to explain the intent of certain laws
  • Political manifestos could include a forked repository with their proposed laws, which anyone could test out
  • New laws (either in Parliament or a party deciding their own policies) could be created as pull requests. MPs, journalists and citizens would be able to scrutinise them
  • The law would be a lot less open to interpretation

What would a country be like if its laws were implemented like that? Are there any drawbacks? The only one I can think of is that developers or technically minded people at least would have an advantage in understanding law. But then, we're in that situation with lawyers as it is.

  • 4
    $\begingroup$ I think this is called computational law. $\endgroup$ Commented Feb 13, 2016 at 2:13
  • 7
    $\begingroup$ For some reason, the halting problem comes to mind. $\endgroup$
    – EvilTeach
    Commented Feb 13, 2016 at 3:13
  • 2
    $\begingroup$ "When proposing a new law, the program could tell you if it conflicts with an existing law or the situation is already covered by an existing law" - this is provably impossible, unless you restrict what kinds of laws can be created. $\endgroup$ Commented Feb 13, 2016 at 9:40
  • 4
    $\begingroup$ I did my PhD studies at a research institute investigating this: leibnizcenter.org . Their publications will have some details on how far we are on that subject. $\endgroup$ Commented Feb 13, 2016 at 16:20
  • 7
    $\begingroup$ The problem with law is that it is a programming language, but one with many bugs and quirks. That's why lawyers tend to reuse existing [previously debugged code -- language which has previously stoid up to challenge -- rather than trying to write it from scratch and hope they've avoided all the problems. $\endgroup$
    – keshlam
    Commented Feb 13, 2016 at 20:13

16 Answers 16


Not really there are too many things that might matter that a computers must take into account.

Phrased differently: The world contains an infinite amount of information and we have a finite amount of computing power to represent and reason about it.

The main problem is an incomplete model of the world. Humans are deeply encoded to recognize when things are not important and ignorable, and we quickly change our model of the world to adapt. A computer doesn't have eons of evolution to tell it what matters, it would have to have thousands of special cases encoded.

For example

  • Walking up to peoples houses and taking their food -> illegal
  • walking up and taking a candy on Halloween -> legal.
  • Breaking into someone's house while they're home -> illegal
  • Breaking into someone's home while its temperature is high (it's on fire) and some one is inside - > legal and heroic
  • Taking a child's clothes off against their will -> illegal
  • Giving your child a bath when he doesn't want one -> legal.
  • Tackling a man to the ground and punching him -> illegal
  • Tackling a robber in your house -> legal.
  • Driving though and intersection when the stop light turns green -> legal
  • Ignoring the traffic cop in the intersection and obeying the stop light -> illegal
  • Shooting a man dead -> illegal
  • Shooting an enemy soldier while actively serving in the armed forces and obeying the rules of engagement -> legal

There are thousands of conditions that might or might not matter, that are difficult to encode and have billions of possible values. The identity of each person involved could matter their age, nationality, physical size ..., the location, the date and time, What other events are happening, what happened in the days, weeks, years before, what was happening 20 ft, 20 yards, 20 miles away.

Even asking a simple question you would either run the risk of missing a key piece of information, or you have to spend weeks describing everything that happened on that continent in the last 5 years in minute detail, and you still might miss something. You can't enumerate all the conditions because there are too many and some have not been hit yet.

In response to comments In robotics this problem of taking only important variables is called the frame problem, and is yet to be solved except in tightly constrained artificial situations.

There are also lots of grey areas where is some thing a crime and would this get you convicted in court are different "a reasonable person's judgment" comes into play

First sentence guidelines are provided by the law a jury actually chooses the sentence. The computer can not know the sentence without knowing the jury and how they would react.

Second Inference is a key part of most trials. We never know what happened: we just have evidence, sometimes very little. In deciding if a crime was committed, a lot of inferences need to be drawn. So, in deciding if something would be convictable as a crime, the computer would have to draw inferences that various juries would draw from various sets of evidence that could come up about the event.

  • 29
    $\begingroup$ Several of these aren't really "special cases", but rather one rule taking precedence over another in situations where that (more specific) rule applies. For example, your "shooting a man dead" example would be the general (fall-back) case, which would be overruled by some more specific rules (such as soldier in a war, or police officer on duty within their jurisdiction, or self-defense). Rule precedence is a fairly well-understood problem in computer science, so I would think that part would be quite easily solvable. (Encoding the content of the rules, now that's a different matter.) $\endgroup$
    – user
    Commented Feb 13, 2016 at 9:03
  • 1
    $\begingroup$ @LieRyan And what I am doing is contradicting the claim in this answer that Not really there are too many things that might matter that a computers must take into account.. If law can be implemented by strong AI (almost by definition it can, as you pointed out) then – assuming that strong AI is implementable (I hope not, I fear yes) – the answer’s claim is wrong. Of course, if law can be implemented with weaker forms of AI, then this answer is even more wrong, but I wouldn’t argue it can. If it can’t, then there is some truth in this answer. $\endgroup$
    – gaazkam
    Commented Feb 14, 2016 at 4:01
  • 4
    $\begingroup$ I don't understand why all of these special cases can't be included in the code. It's more work, sure, but most of these things are covered by existing law, so writing them as formal code doesn't seem like too much of a stretch. $\endgroup$
    – ckersch
    Commented Feb 14, 2016 at 16:45
  • 5
    $\begingroup$ "Tackling a robber in your house -> legal." Depends where you are, sadly. $\endgroup$ Commented Feb 14, 2016 at 18:29
  • 1
    $\begingroup$ Everything that isn't explicitly made relevant in the legal code doesn't matter, which is almost everything. Everything you have mentioned as an exception, for example, is already covered in the legal code. Why do we need more exceptions that what is already there? $\endgroup$
    – ckersch
    Commented Feb 16, 2016 at 23:46

Yes, given some limitations and assistance.

It wouldn't be so much an artificial intelligence or natural language processor so much as a database of relationships between entities. However, some legal language left over requires a human's intellect to be able to really reach an accurate answer.

You're restructuring legal code to be relationship-based. You could have an enumeration of intentions, such as "deliberate" or "by negligence." You could have an enumeration of public status to determine if a person is of official title or office, or in a position of authority, which would make certain actions illegal for them but legal for others. Your computer program would be massive and its database would have an incredible amount of tables.

With enough data, anything is possible.

You're still forced to keep your program very simple without any room for the human element. Distinctions such as "forcible" for sexual assault or "excessive" for police are not answerable without the usage of an advanced artificial intelligence or a human on stand by. This makes your program unable to deem a perpetrator's sentencing.

There's still nuance and interpretation left over. For example, what about unanswerable questions?

What if I have the following query (C# LINQ style):

bool isLegal = incidents.Where(i => i.Perpetrator == i.Victim).First().Select(i => i.IsLegal());

Great, now we have an incident query where the perpetrator's the victim. Or worse yet, victim == null is true. There's no victim. What does the program do?

Your program would be a fancy legal version of Mayo Clinic's symptom checker. Another good data set is the ICD (International Classification of Diseases) code set (Example here.) Sure, you can look at them and draw conclusions from them and quickly retrieve certain answers with known data and relationships among finite data sets, but without incredible intelligence, you will never use it as a standalone tool that everyone can use to replace the courtroom.

So for your benefits, all of them would be fine and good, but you will still have lawyers to understand precedence and how it relates (in an abstract way) to a new incident, and you still still have jurors to interpret the information. The amount of edge cases is too huge, and you still require the nuance of understanding things like intent, premeditation, etc.

And who actually uses the program? Sure, it might be good for teaching students but it's a needle in a haystack. For the ICD codes example, would a non-doctor know to search for iodine deficiency?

These things are abstract and it can still be too complicated without a specialist in law.

  • 5
    $\begingroup$ +1. There are some areas of the law that are especially appropriate for computational law, like the tax code. And I do not think that the law needs to be fully automated; For instance, you could have function calls like accused.hadMensRea() or patent.requiresInventiveStep() that would wait for jury I/O. The law would then memoize this value so that it never accidentally asks the question again and proceed, stopping as many times as needed for jury I/O. Then the law could pass judgement following very logically the trial procedure. $\endgroup$ Commented Feb 13, 2016 at 2:25
  • 2
    $\begingroup$ In real software, I note that expert systems use "forward chaining" instead of "backward chaining" so they don't ask for (e.g.) lab analysis and medical tests to be performed until they figure out everything that can be figured out from information already given. $\endgroup$
    – JDługosz
    Commented Feb 13, 2016 at 18:36

From a certain perspective, a legal system is in itself already an attempt to codify/operationalise morality – it's an attempt to express as explicitly as possible what behaviour is immoral, and to punish/disincentivise immoral behaviour in ways that are themselves moral/ethical. Without a code of laws, "right and wrong" are determined by either an individual in charge, in an autocratic society, or via debate/reasoning amongst some or all members of the community, in a society without a clearly delineated hierarchy. We can't know for sure what motivated the first attempts to operationalise and record a consistent set of rules for living, but one might intuitively presume a few motivating factors:

  • Ensuring consistent application of the rules in every case (itself something which must have been deemed ethically important)
  • Deflecting the "well that's just your opinion, man" defence
  • Allowing whoever had the authority to make the rules to delegate to others, while still ensuring that their own values would be represented

What's interesting is that the earliest known legal code, the Code of Ur-Nammu was a series of if statements:

  1. If a man commits a murder, that man must be killed.
  2. If a man commits a robbery, he will be killed.
  3. If a man commits a kidnapping, he is to be imprisoned and pay 15 shekels of silver.
  4. If a slave marries a slave, and that slave is set free, he does not leave the household.
  5. If a slave marries a native (i.e. free) person, he/she is to hand the firstborn son over to his owner.


  1. If a man had let an arable field to a(nother) man for cultivation, but he did not cultivate it, turning it into wasteland, he shall measure out three kur of barley per iku of field. (29)

In other words, from a certain simplistic perspective, it was already a "program" of sorts, one that was to be executed by humans instead of computers. The problem that's immediately apparent, and which other answers have already described, is that the application of these rules has not itself been operationalised. What is murder? What is robbery? Who may legally be made a slave in the first place? And so on. In other words, if statements are an imperfect mechanism for operationalising ethics; you end up requiring a potentially infinite series of clarifying definitions and decisions. My suggestion would be to return to first principles, ideally, and create an artificial intelligence that is capable of making moral decisions, using structures and methodologies that are more powerful than simple if-then constructions. We would want this AI to have the same fundamental morals as the majority of the humans who are planning to create it and subject themselves to its will, while hoping that it would uphold a purer version of these morals, immune to bias and corruption, and incapable of being manipulated or tricked into making an immoral decision.

In other words, you'd be creating a god – a perfectly Good god, at that, as opposed to one of the fallible, relatable ones that exist in religions such as the ancient Greek. I'm not pretentious enough to claim I have any definitive ideas as to how this can be done, but I'm fairly confident it can't be done with nested if statements. What might work:

"Moral calculus"

One fairly acceptable basis for moral reasoning is utilitarianism. Assuming that all individuals are of equivalent worth, then it's optimal for the largest number of individuals to experience the greatest possible satisfaction while experiencing the least possible discomfort. Loosely define what is good and what is bad at the most fundamental level; death and pain are bad, joy (perhaps measurable in humans via endorphins, serotonin, and so on) is good, and so on. Now we have the kind of optimisation problem that AIs are already getting moderately good at trying to solve. Now we're barely dealing with ethics at all, we're dealing with causality. An action that causes another human to die, or to experience pain, or to be denied their 'fair share' of pleasure is bad, and should be prevented/punished. A person's 'fair share' of pleasure can itself be defined as what they can experience without causing death, pain, or excessively diminishing the ability of others to experience their own fair share of pleasure. I find it hard to disagree with any of the judgements that my limited human mind can predict arising from decisions made according to this kind of "moral calculus". This kind of reasoning not only determines how humans should behave, but also how the AI and it's agents should behave – punishment/deterrence should take a form that prevents wrong by inflicting the bare minimum of death/suffering/deprivation to offenders, actual or potential.

There's one catch here – if the system is counting deaths, and measuring pain and pleasure, it's only capable of deciding retrospectively. This works for 'delivering justice', but it doesn't necessarily help in terms of guiding people as to how to make moral decisions as to how to act in the first place. The system could of course make general guidelines based on the collected observations of past decision-making processes, but the better (and more interesting and/or terrifying) approach would be if it were capable of accurately simulating all possible decisions, and the outcomes of those decisions. Now we're really talking about a god – without deviating too much from the topic at hand, consider that an accurate simulation of a human consciousness is considered by some to have equivalent moral rights to a natural-born biological human; but if our AI god wants to test the effects of various actions to determine whether they are immoral, and to what extent, it's going to need to simulate victims as well... Is this permissible according to its own moral reasoning? Maybe it is, since it would enable it to justly govern an indefinite number of real humans. But it's a lot easier for the super-AI to create humans than it is for humans to create humans, and it can create more of them than the physical Earth could hold – so maybe their rights, in the end, outstrip your own?

Totally unnecessary extension, with apologies to Eliezer Yudkowsky and friends

How do you know you're not already an agent within the simulation of an AI attempting to determine how humans should behave?

  • 2
    $\begingroup$ If the AI uses utilitarianism principle to maximizes joy by measuring endorphines, it would make it mandatory for everyone to be injected with drugs. $\endgroup$
    – Lie Ryan
    Commented Feb 14, 2016 at 3:53
  • $\begingroup$ @LieRyan I'm familiar with that idea, but I thought I'd gloss over it for now. The hardest part of this problem (aside from, you know, creating super AI) is the first part — deciding what core values to start with. You wouldn't want to just use endorphins, or oxytocin, or anything that basic. You'd need to map observable factors to these true values, define acceptable bounds, relations between variables — as I mentioned, I'm not pretentious enough to actually try and figure this out for real! $\endgroup$
    – Toadfish
    Commented Feb 14, 2016 at 3:56
  • $\begingroup$ It's a total cop out, but you would need superhuman intellect and all conceivable data on the human experience to even begin defining your utility functions. Create your newborn God, and say "well, this is us. What the hell makes us happy?" — and then hope against hope it comes to conclusions you can accept. $\endgroup$
    – Toadfish
    Commented Feb 14, 2016 at 4:01
  • $\begingroup$ Interesting first half of the answer, but I think it's a bit of leap that because we'd have to define murder (and hence define death etc) we'd have to make god-like AI to come up with our laws from first principles. The definition of murder must be written down somewhere in existing laws and presumably that in turn refers to the legal definition of death, which is probably based on a doctor signing a death certificate, then that could easily be used as input to the program. $\endgroup$
    – Gnuffo1
    Commented Feb 14, 2016 at 18:24
  • $\begingroup$ @Gnuffo1 I may have taken an overly extreme interpretation of the question, one where we're looking for a computer/program that could run a perfect justice system without any human intervention. I'm sure a more achievable expert system like those written for medical diagnosis would be capable of taking over certain parts of our existing legal systems, like you've described. $\endgroup$
    – Toadfish
    Commented Feb 15, 2016 at 10:37

Within the rules of the American Contract Bridge League is a particularly important one. Paraphrasing from memory, no player may deliberately violate the rules of the ACBL, even if the penalty is one the player would otherwise accept. Proven violations of that rule are to be punished severely, even if the punishment for the underlying infraction would otherwise be relatively minor.

While enforcing such a rule is, of course, difficult (since it would require knowing the intentions of the accused) it is nonetheless extremely valuable, since it highlights an important principle: the legitimacy or illegitimacy of an act does not depend upon whether or to what extent it may be punished. Someone who deliberately leads out of turn for the purpose of passing information to partner is cheating. The fact that the tournament director may be unlikely to seriously punish someone who lead deliberately out of turn but could plausibly claim to have believed he was on lead would not make the action legitimate; it would merely mean the player was an unpunished cheater.

A legal system establishes guilt and punishments in any kind of formulaic fashion, no matter how carefully the formulas are designed, will allow those who are familiar with the system to profit substantially by cheating to an extent which falls just short of the threshold required for a punishment exceeding the benefits of cheating. A good legal system should have a certain tolerance for honest mistakes, but in a formulaic system any such tolerance will be exploitable by cheaters.

What's needed instead is a recognition that minor cheaters will often go unpunished, society owes them no obligation in that regard. Unfortunately, no deterministic way of catching cheaters will be effective at those who can arm themselves with the knowledge necessary to game the system. What's necessary is to have a legal system that can make judgements which go a level beyond anything a cheater would be able to predict--one which can go beyond "Is there level XX of evidence the person tried to cheat", or "Is there level YY of evidence that the person was trying to keep the evidence of cheating below XX", to "Was the person trying to cheat and game the system to get away with it". And I don't think a formulaic legal system will be able to accomplish that.


While there are no software based/generated law systems yet there are some attempts to process law algorithmically. For instance the Indect project involves searching for possible crime in data sets written in natural languages. It differs from your idea in the fact that the law needs to be encoded in some computer readable form (for instance XML or Java) and this format of rules, even if equivalent to the original in mathematical/logical sense is not normative per its own. The algorithm just finds cases to be examined further.

If you would like to go one step further and make some XML description of rules normative in legal sense, the major obstacle would be human factor. You seems to be too widely inspired by github subculture and not aware of how non-programmers perceive law. They may be against such innovation for several reasons:

  • Judges would lose their job or at least their authorty/independence as their decisions could be objectively tested.
  • Society would fear that they do not understand the new XML-encoded rules. I guess you would have to at least generate a natural language normative text from your XML/Java code in order to avoid such suppositions.

At the end judges will still decide and software would be only help in cases where they do not want to abuse the system. Or in other words: the law will still remain open to interpretation. At least it would stop being inconsistent (what btw would be a huge achievement too).

On the other hand some of problems already mentioned by you or in other answers would be not a problem at all:

  • Lawyers would not disappear as asking such computer oracle will still require some knowledge to pose a question (see: Wikipedia is not a help if you don't know what keyword to search for).
  • Although such approach would allow some form of automated testing, I thing there would be no "forking repositories", "test driven development" etc. like ones in IT. Government is made mostly of non-programmers (assuming you do not abandon democracy) and I would expect them to continue working and thinking normal, paper-based way.
  • Citizens are not programmers so they would not run automated tests. Manifestos would still be natural language based populist bullshit.
  • Public availability and comments are elements existent in contemporary law systems, it wouldn't change a lot.
  • Fuzzyness / too many things that matter would not be a big problem. Now we are copying with such cases by involving lay judges who decide by their intuition. There is no reason to avoid it, as humans will continue to know better what feels moral to them than AI.

    Imagine a case of divorce where it needs to be decided who of parents should take care of the children but both of them lie to their advantage and it needs to be decided not only logical consequences of known facts but also which facts one should believe.

    The law computer system will just have defined situations (a lot of them…) where human assessor decision is needed.

Nevertheless, other problems may emerge:

  • As you said, the program could tell you if it conflicts with an existing law. But because of Gödels' incompleteness theorem and of stop problem there would be cases where such queries would be undecidable with no chance of a program detecting the undecidability. It would just hang or provide something like "no answer found in time limit".
  • Because of that we would need to base our system on some paraconsistent logic instead of classical one. By the way using paraconsistent logic would solve also problem of existing nonconsistent law.


While this might work for most cases, it won't work for "hard cases" - stuff that depends a lot on circumstance, or where there is no precedent - for example most cases involving slayer laws or in emergency situations such as the speluncean explorers (where some of the decisions are based on stuff such as what does the public want, or if there is an expectation of executive pardon)

It also fails to ensure that the law is enforced as intended - for example Adultery is illegal in many places, but not prosecuted - is this a law? - times changes, opinions change - be it if alcohol is legal/illegal, marijuana, LGBT, etc. - and normally society changes before the written law changes, so if the written law was enforced as written, then there would be many problems.

Computers are also horrible at reading intent or motives, which is a critical part in evaluating many laws, such as what supercat's answer wrote - consider anti-monopoly laws where a large corporation may be willing to accept the slap-on-the-wrist fine while enjoying huge profits - or big Phara companies suing each other to continue being the sole source of drug X, and thus get an injunction preventing anyone else from selling X, even if their patent has run dry because of bogus quality concerns or other issues - they continue getting tons of $, at the relatively minor costs of lawyers in comparison. Or what happened with lavabit when it technically complied with a court request to turn over it's SSL keys, and they did so by printing it in a tiny font


Yes it could

We already have legal software capable of giving legal advice.

But that won't allow you to automatically hold a court

The essence of courts is rights protection, not mechanically forcing the law. The law is the tool here, not the purpose. Nowadays people are being condemned for infringing on somebody's rights, not just for "breaking rules" (as they were in medieval times). Any contemporary legislational system is more complex than just a set of rules what is allowed and what isn't (e.g. Judiciary).

Some of your suggestions are already implemented

You could ask it if an action, given certain conditions and involving certain entities, is legal or illegal and what the sentence is. Would we still need lawyers to advise us?

As I was saying, there are already such kind of software. But, due to subjective nature of legislation, that doesn't work so well as, say, mathematical software. We still need lawyers because a lawyer isn't just a walking dictionary (neither is any specialist). We have MathLab but still need mathematicians more than before.

When proposing a new law, the program could tell you if it conflicts with an existing law or the situation is already covered by an existing law

Possible conflicts is actually the lesser evil. Possible exploitations are more dangerous. To reasonably propose a new law, you need to predict its behavior in real environment, that's what experts do.

The code could be publicly accessible for anyone to examine and test scenarios and potential new laws

Normally, most of statutory wordings are already accessible. They haven't be a code for that.

Comments could be added to explain the intent of certain laws

That is already implemented. Again, you don't need a computer program to add comments.

New laws (either in Parliament or a party deciding their own policies) could be created as pull requests. MPs, journalists and citizens would be able to scrutinise them

I suppose, you're talking about democracy or meritocracy (technocracy). Check Athenian democracy or how laws are made in the US.

The law would be a lot less open to interpretation

The openness is actually "a feature, not a bug". Google "equity of statute".


Yes this question is old, but some beancounters really ticked me off again today.

Most of it can be automated.

I'll first give some codex samples as a Java MVC, and at the end I'll post comments about common misconsceptions non-developers seem to have

I envision this to be a sort of REST-like service onto which various agencies and law firms can slap their own UIs on.

The job of politicians would probably end up being the writing of the test cases. That way they can show (or prove to) their constituents the effects of their proposals directly without having to know too much about software engineering.

Tax Code

in TaxCode

Residents residents

Post post

private void income(){
  for(Resident resident : residents){
    var income = resident.getLast12MonthsIncomeStatements().sum();
    var deductions = resident.getLast12MonthsDeductibles().sum();

    var taxable = income - deductions

    double rate = 
      (taxable < 10000) ? 0.20 :
      (taxable < 20000) ? 0.30 :
      (taxable < 50000) ? 0.40 :

    post.dispatch(resident, createBill("your tax office needs", rate*income))

in Resident (extends Person)

public void addDeductible(String deductibleType, Currency expended, String comment){
   default: throw new IllegalDeductibleType(deductibleType);


in Visitor (extends Person)

Executables executables;

Police police;

public Visitor(PersonDetails personDetails, String visa){
  Date expires;
    default: expires = new Date();
  executables.add(expires, ()->{police.deport(this);})


in Crime.Victim.Murder

public class Murder extends Deceased implements Victim{

  final static Sentence sentence = Sentences.murder;

  Police police;

  public Murder(Person victim){

  public void addPerpetrator(Person person){
    assert(person != victim);

  public void clearPerpetrator(Person person){

in Crime.Sentences

public static final Sentence murder = Sentence

public static final Sentence jayWalking = Sentence


in Agency.Faa.PilotLicense

public class PilotLicense extends License{

  boolean active;
  String comments;  

  PilotDatabase pilotDatabase;

  //anyone can do this
  public PilotLicense(MachineReadableDocument pilotExam){

    assert(pilotExam.type == "Pilot Exam")
    assert(pilotExam.grade > 0.9)

    super(pilotExam); //authenticates the exam

    active = true;

  public void suspend(){
    active = false;

in Agency.IRS

public class IRS{

  Residents residents

  Person getNewCase(){
    return residents.getRandom();  

in Person

public void pardon(){
  this.crimes = null;

Comments for laypeople

  • Conflicts: Conflicts in the law do not happen. If the arise, the law will not compile.

  • Ambiguity: There is no ambiguity. Properly codifying the law will force politicians' feet to the fire and expect them to specify what they want in exact terms. If ambiguity arises, the law will not compile. Do note that it is possible to create an ambiguous interface, (as in, you create Murder and Premeditated Manslaughter and people aren't sure what the difference is) but such situations shouldn't be created in the first place. If judges and juries are confused about which crime to apply, the politicians didn't do their job right and should be accused of obfuscation.

  • Case Law: Case law should not exist. Judges and juries should not make laws. things that can happen are the following:

    • a use case (e.g. crime) is not implemented: in this case, the legislative branch must decide what to do.
    • people are unsatisfied with the sentence a criminal receives: in this case, the legislative branch must reevaluate their test cases.
    • there is a mistake/technical error in the code: well the result gets ignored until it gets fixed, obviously.
  • The Role of Courts: Courts, Judges, Juries etc, exist only to translate the physical world into the digital world: they classify crimes. The sentence is determined by the system.

  • Security: the only thing that needs to be secure is the State repository (people-database, or the Model). Access needs to be managed, logs kept and routine backups made. Functions that can be executed by certain roles are annotated as such (e.g. @Secured("JUDGE")) everything else can and should be publicly viewable.

  • Special Cases: regarding @sdrawkcabdear's post: if nobody reports the crime, it might as well not have happened. and if someone steals something, a judge registers a crime with a perpetrator and a value. A burglary is at least Tresspassing and Theft/Misappropriation. On halloween you're not trespassing if you're invited, and you're not stealing if someone gifts you candy. I don't see how this post is so highly rated as it doesn't make much sense to me. In any case, those are all judicial issues, not legislative ones.

  • Artificial Intelligence: this has nothing to do with artificial intelligence.

Closing Remarks

this needs to happen ASAP. with ~ 15% of the workforce dedicated to government, it accounts for probably at least 30% of government expenditure

considering police ( executive ) is usually only ~ 0.3%, it makes you wonder what all these people are really needed for.

Yes I'm salty. Saltier than the Don Juan Pond.

  • 2
    $\begingroup$ Land o' Goshen! +1 for the effort! Welcome to Worldbuilding.SE. Please take a moment for our tour and our help center to learn more about us. $\endgroup$
    – JBH
    Commented Jul 10, 2018 at 21:25
  • $\begingroup$ @JBH is there anything specific you want to draw my attention to? $\endgroup$
    – option 12
    Commented Jul 10, 2018 at 23:19
  • 2
    $\begingroup$ Heck no! I came in to evaluate a new user's post and thought to myself, "Now THAT's an answer!" Cheers! $\endgroup$
    – JBH
    Commented Jul 10, 2018 at 23:41

Given what assumptions?

If you're going to postulate an Artificial Intelligence that can do anything a human being can do, then presumably by definition the answer is yes. So I'm going to assume you mean with current technology or something reasonably close to it.

Next question: In what sense?

In the simplest sense, it would certainly be possible to store the law on a computer and make it easily searchable, have cross-links between related laws, etc. I'm really surprised that more hasn't been done in that regard. The technology exists to store the text of the law on a computer in HTML, create abundant links, provide text searches, etc.

The first place where it gets tough is when you say things like, the computer will tell you when a proposed new law conflicts with an existing law.

Some cases would be easy. If someone proposes a law reading, "The speed limit on interstate highways shall be 85 miles per hour", I could imagine a computer being able to find that there is an existing law that says, "The speed limit on interstate highways shall be 80 miles per hour".

But what happens if you say the same thing in different words? Like what if someone proposes a new law reading, "No one shall be allowed to drive a car more than 85 miles per hour on roads making up the interstate highway system." Now the computer has to figure out that "interstate highways" and "the interstate highway system" are the same thing. That may seem obvious, but just because two phrases share common words doesn't make them the same thing. How would it now that those two are the same but, for example, "the Marines" and "the merchant marine" are very different? How would it know that a "speed limit" refers to the top speed you can drive a "car" and not, say, a boat, or oil through a pipeline? How would it know that "speed" here means "velocity" but in another law refers to a drug that acts as a stimulant? Etc.

What happens when a law entered into the computer is ambiguous? Like in my example above, does this speed limit apply to trucks and motorcycles?

Many laws are very subjective. For example, to successfully sue someone for negligence, you have to show that he did not take the precautions that a "reasonably prudent man" would take. Who is to say what a "reasonably prudent man" would do? That's full of subjective evaluations.

Similarly, I'm somewhat active on a forum for writers, and a question that routinely comes up is, Copyright law says that I can copy short quotes from another person's work without permission. What is "short"? Can I copy 50 words? 100? 1000? There is no hard number. The law further says that factors for the court to consider when deciding if such copying is "fair use" are whether it was copied for educational or research versus commercial purposes, the nature of the work, etc. What makes something "educational"? What about "the nature of the work"? Etc.

Laws do this very deliberately because there is the constant struggle between the letter of the law and the spirit of the law. Someone else mentioned that the law forbids breaking into someone else's house -- but no one's going to prosecute you if you did it because the house was on fire and people were screaming for help. It's against the law to take someone else's property without their permission. But if a maniac is holding people hostage, and in a moment of carelessness he puts down his gun and looks the other way and one of the hostages grabs the gun, I really doubt the hostage would be prosecuted for stealing. Etc.

Perhaps you wouldn't simply type English text into the system, but would have to describe laws using a carefully-defined language that eliminates a lot of these complexities and ambiguities, a language designed to describe laws in a way that a computer can process and analyze. But would it be possible to create such a language? To say, "Yes, the computer can solve this problem. We just have to invent a language to describe the problem in a way that the computer can solve" is to talk in circles. Like, "Yes, I can prove that it is possible to build a spaceship that travels faster than light. You just have to grant me the one tiny assumption that someone else will provide me with the plans for a faster-than-light engine."

So in conclusion: I'm quite confidant that it could be done in a limited way. But to meet all the conditions you describe? That would require advances in AI far beyond what anyone has accomplished to date.

  • 1
    $\begingroup$ A fundamental difficulty is that in many cases just laws need to consider the state of mind of the accused at the time of the offense, but since that cannot be directly ascertained it is necessary to make inferences about it on the basis of overt acts. There is a fundamental difference between someone who is trying to avoid damaging someone's property but accidentally causes \$10 worth of damage (which is below a \$20 minimum for the victim to seek compensation), and someone who is trying to cause as much damage as he can without any risk of exceeding \$20. $\endgroup$
    – supercat
    Commented Feb 13, 2016 at 20:19
  • 1
    $\begingroup$ A malefactor who knows by what means his state of mind will be judged could do great mischief if he could as a consequence act in such a way that his motives would appear clean by that means. If that means where the only one by which punishment could be assessed, such a malefactor need not even bother keeping his motives particularly secret, provided that the means by which he made them known were chosen so as not to be usable against him. $\endgroup$
    – supercat
    Commented Feb 13, 2016 at 20:22
  • $\begingroup$ I think with your example of the computer not knowing if laws phrased in slightly different ways apply to the same thing, that laws wouldn't be defined in such a way. Rather than trying to parse a sentence written in a human language, you would define entities / classes such as "Vehicles" and sub types of these such as "Car", "Bus" etc and then various actions such as "drive" which would have attributes such as "speed" and other entities this would relate to such as "roads", which again would have sub-types. $\endgroup$
    – Gnuffo1
    Commented Feb 13, 2016 at 23:09
  • $\begingroup$ @Gnuffo1 Yes, see my paragraph beginning "Perhaps you wouldn't simply type English text". But you run into the problem that if everything you can write a law about is in menu picks, drop down boxes, whatever, then sure, if you want to change the speed limit or the threshold from petty theft to grand theft, you just navigate to the right place and type in the new number. But if you want to write a law on a subject that we didn't previously have laws about, the software must be updated. And most laws have lots of detail. Would all this be in drop-downs? How? $\endgroup$
    – Jay
    Commented Feb 14, 2016 at 23:05
  • 1
    $\begingroup$ Lots of what makes up the body of law isn't in the text of the law itself; it's in preparatory studies of various kinds, previously decided cases, etc. Law is often purposely vague in some areas (while highly specific in others), and courts turn to this supplementary information in order to decide in a particular case, in the process refining the legal precedent further. $\endgroup$
    – user
    Commented Feb 16, 2016 at 12:35

I think it's a fascinating idea. But it's easy to misunderstand the concept. I've had this idea in my head for a little while also. I think if of it as just replacing the human language representation of the law (eg, English) with a computer language representation. That is, the actual meaning would remain the same. Just the language has changed. In theory, computer languages are our best attempt that representing complex logic so maybe it make sense.

It's interesting to think about how this could apply to financial law (eg, for investments or tax laws). Perhaps it could lead to a kind of arms war. If financial law was expressed completely as a computer language it would be easily to apply game-theory type methods to find the practices that produce the highest returns.

We've already seen computer processing power have an effect on the stock market through algorithmic trading. With more powerful hardware and better algorithms are, you can make faster trades and get a competitive advantage.

But we could take that to the next level with algorithm that find the best way to minimize tax. Or they could find the best way to restructure a company to avoid regulation.

Perhaps this would mean that loopholes in the law would become instantaneously obvious and available to everyone. For example, in the past there have been legal loopholes that allowed organizations to behave like a bank even though they were not regulated as a bank.

But the impact of that problem was minimized by the fact that it was difficult to understand that this was the case... But with computational law, this kind of thing could become obvious.

How could lawmakers respond to this? In some cases it might be possible to also instantaneously close loopholes. But sometimes loopholes can't be closed easily -- even when we know they exist. For these cases, we would have lost the "fog of war" that comes with the esoteric nature of law.

So, this is our arms race: a race of finding loopholes against closing them.

This same kind of thing could be applied to non-financial law, also... I remember after the George Zimmerman case, some media pundits worried that the verdict effectively legalized murder, under certain circumstances.

In a computational law world those "certain circumstances" would be more clearly understood. As a result they could also be more easily taken advantage of.

Maybe all of this could lead to a system of laws that was constantly changing (like a large open-source codebase, or like wikipedia).

If a character wanted to do something that was on the line between legal and illegal; it might be interesting if he could run a search that looked at recent court verdicts and waited for that short period of time in which his activity was (technically, computationally) legal.

It might also be interesting to think about the organizations that create programming language (such as the C++ Working Group) as prototypes for future law making bodies.

  • $\begingroup$ A program like Watson might do such a search. $\endgroup$
    – JDługosz
    Commented Feb 13, 2016 at 18:32
  • 2
    $\begingroup$ The problem with law is somewhat analogous to one in mathematics: there is no way to construct a non-trivial system of rules in which it is not possible to construct situations that the rules cannot cover. Any rule which would cover all situations not covered by the previous rules would necessarily allow the construction of new situations which it doesn't cover. The only "way out" is to acknowledge the necessity of rules which cannot be expressed within the system. $\endgroup$
    – supercat
    Commented Feb 13, 2016 at 20:12

What does the input look like?

If you are already doing the “interpretation” of the crime and the input is something like “forcible entry, 20 year old” then it becomes a relatively simple lookup like this Symptom Checker. It depends on the proper formulation of the input and a matching entry. Laws are already formulated with criteria which have to be fulfilled, exceptions, precedence and so on.

If you want to present the computer with a verbal story then it has to interpret human language with all its implied meanings, incompleteness and vagueness. In which case you’d need an AI which is prone to the same misunderstandings as a human (though at least you could program it to be impartial and without emotions). Automatically looking up the appropriate law after the interpretation of the case is the easiest part of the problem.


Coming at this from a technical (instead of legal) side, you are going to have giant issues with security. With computers, the only secure computer is one that no one can access and doesn't have power. If the computer is connected to anything (and if you are allowing access to it, then it is), then it can be hacked. This means that people will try hacking in to change laws they don't like or (if the computer is also acting as jury) make sure that a specific verdict is carried out or sentence assigned. You are also going to have people trying to bring down the system as a whole either as a prank or as an attack.

You are also going to have issues with how you present cases to the computer. It will likely need to be a very formatted input so that the computer will understand. Depending on the programming, you might get multiple answers for the same issue by inputting it differently. In that form, lawyers will become very valuable again. Instead of learning how to present the case to human judges and juries, lawyers will train in how to input the facts to the computer in such a way as to sway the output.

  • $\begingroup$ For your first point, if the laws and judicial systems are open-source (as they should be), people can just rerun the program on their own computer to check the verdict. Your second point is probably spot on. $\endgroup$ Commented Feb 16, 2016 at 11:31
  • $\begingroup$ @Stig Even with it being open source, you are going to have people trying to place "cheats" into the code (do this weird combination of things to get off totally free). You are also dealing with a population that doesn't, for the most part, really understand how computers work. People already have enough issue with using computers. I can easily see malware being created that instead of stealing personal information messes with the response you get back for legal questions. $\endgroup$ Commented Feb 16, 2016 at 13:11

Primary Benefits

A fully codified (dare I say "executable") legal system lends itself well simulation. Instead of ideological debates about what the law should say, simulations can be run to see what would happen if a given version of the law was applied.

Because the law is code, a great many software coding tools can be modified to operate on the legal code. Static analysis, delinters and a host of other tools can be brought to bear to eliminate or minimize syntactic and semantic errors in the code.

It's not hard to imagine a kind of Legal Github where the entire legal code base is a git repository that anyone can use to fork, modify and/or send pull requests. Someone will still have the job of accepting patches and integrating them into the code base, like a Legal Linus.

Primary Detriments

First, this is hard. Conceptually, yes, a program or set of programs could encode law but given the near infinite degree of variation in circumstances coupled to the ambiguity of natural language, this is a really difficult problem. The development costs associated with codifying and managing the code may prove to be significant. And, don't forget that most large software projects are canceled because of functional problems and significant delays. Replacing a national legal system overnight is almost sure to fail.

Have a look at ratio decidendi . It's a legal concept meaning "the point in a case that determines the judgment" or "the principle that the case establishes". Your coded law will need to be able to determine and reason about the ratio decidendi. This is impossible for many humans and difficult for those who can.

A codified legal system may be as easy or easier to exploit than existing legal systems. Extracting loopholes, inconsistencies or unregulated areas will be much easier with the power of distributed computing.

Encoding a Legal System

As David Friedman shows in "A Legal System very different from Ours", there are many different ways to build a legal system and different ways of describing then enforcing penalties on offenders. Whoever writes the code must choose to either use the existing legal system with some modifications or perform a "rip and replace". (Note that rip and replacements of legal systems are incredibly rare and monstrously expensive. Organic evolution is far more likely.)

Incorporating Case Law

Most legal systems are composed of two sets of laws; the law itself and commentary on the law. In legal systems descended from England, this duality of legal code appears as the Law and case history. Generally, case law confirms what the law states (in as far as that can be determined from the law) but there are instances where the two not only diverge but oppose each other. Designing a system to handle these kinds of inconsistencies will be hard....Well, detecting them shouldn't be too difficult. Reasoning about them is hard.

What would a country be like?

Making law - Still done by politicians. However, instead of lawyers becoming politicians, in this case, it would be software developers and technologists as the law makers. They understand code better. A pointer to what rule by technologists might be like can be had in China where many of their highest leaders are engineers.

Enforcing law - No change. Enforcing the law still requires police, prosecutors, judges and the penal system (in whatever form that may be; incarceration, transport, indentured servitude). How they go about enforcing the law may change but the instruments required to enforce will not.

Degree of Injustice - Difficult to tell. This will depend heavily on the culture of the people of this country and the quality of the legal coding. I can imagine instances where there's radical improvements and I can imagine radical exploitation of the unprivileged (which is no different than today).


This would work very well if you have a set of rules like the Ten Commandments (except you would have more laws than 10 presumably). In this case the computer could easily tell if a law had been broken and apply the sentence.

As you add nuances such as multiple different sentences that could be applied for a single crime e.g. amount stolen leads to a different sentence it becomes more difficult but still fairly easy as there are still set sentences that can be worked out.

Where the system breaks is if you have a murder vs manslaughter case. A computer will struggle to calculate intent and human emotion/provocation and will probably be slower and less accurate than a jury. So you would still need experts to sort out these cases based on human emotion.

  • 1
    $\begingroup$ I'll let anyone who is Jewish call me out on any technical mistakes I make here, but from what I have read, the "10 commandments" is actually a mistranslation. "10 speakings" is probably closer to the meaning of the Hebrew. "Mitzvot" is the Hebrew word better translated as "commandment." There's 613 of those, not just 10. The 10 speakings or 10 commandments are typically thought of as headers which can be used to organize the mitzvot! Meanwhile, the interpretation of those 613 is the source of quite a lot of complicated decision making that could fill as many legal valumes as the US code! $\endgroup$
    – Cort Ammon
    Commented Feb 12, 2016 at 22:24
  • $\begingroup$ With "Thou shalt not kill" you break the law by using antibacterial soap. $\endgroup$
    – Samuel
    Commented Feb 12, 2016 at 22:25
  • $\begingroup$ @Samuel Well, that makes the computer even harder to create as miss-typing your code would lead to problems like that. $\endgroup$ Commented Feb 12, 2016 at 22:34
  • 2
    $\begingroup$ Even the ten commandments are hard to encode for a computer, thou shalt not kill. How do you teach a computer what killing is? You need to define life and other things. The defenition of what is "alive" is a many front ongoing debate now see the abortion debate on when life starts, the ending life support and assisted suicide debates on when it ends. If we can't define life how can we teach a computer to define killing? $\endgroup$ Commented Feb 13, 2016 at 1:31
  • $\begingroup$ @sdrawkcabdear True, I was picking the ten Commandments as an example of a set of laws with no subtleties. I get that they aren't easy to program but it would be much easier to program them than a modern law system. $\endgroup$ Commented Feb 13, 2016 at 10:08

There are many good replies, but I want to add a few points.

Merge Conflicts

The concept of repositories, branches, and commits brings you merge conflicts. While a change to the existing law was debated, another change was voted which directly or indirectly affects the proposal being debated.

Automated Testing

You would need to specify cases for the test suite. Who does that? If a commit breaks the test, does that mean the merge is rejected or does that mean the test is obsolete? Are the automated tests part of the "source code" which needs to be voted in?

  • Imagine you have a test case which says "the main perpetrator X (see library of test fixtures) is punished more harshly for crime Y (see library) than the accomplice Z (see library)" and the new law says "double the punishment for repeat offenders." The test case fails, but that was the intent of the new law.
  • There is a proverb that hard (i.e. specific) cases make bad laws. Test cases are hard cases in this sense.

Judicial Precedent

Laws are impossible to understand without knowing how judges will interpret them. This may change at a different pace from the laws themselves.


Who names branches? Can you still campaign for the Anybody Who Votes Against This Is No Patriot act or does it become request #670272578? Or was it #670272587?

  • $\begingroup$ The concept of "judicial precedent" is treated with much more respect than it deserves. In cases where a ruling for either party would be justifiable, it is reasonable to use precedent to decide which party should prevail, but unfortunately judges feel entitled to use precedent as justification for rulings which would not be justifiable in any other way. $\endgroup$
    – supercat
    Commented Feb 14, 2016 at 7:26
  • $\begingroup$ @supercat, we're on Worldbuilding here, a site for building fictional worlds for science fiction, fantasy, or whatever. Are you talking about the real-world US? EU? China? Also, see my answer to worldbuilding.stackexchange.com/questions/12265/… $\endgroup$
    – o.m.
    Commented Feb 14, 2016 at 10:21

Create a jury of AI's.

Take the greatest 12 programmers on the planet, and each have them write their own AI according to the other answers. To convict someone of a crime, a set percentage of the AI's would have to agree on the conviction. This would help handle edge cases as more than one program would have to return the conviction.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .