LOGIC 101

1. Implication

The statement “p implies q” means that if p is true, then q must also be true. The statement “p implies q” is also written “if p then q” or sometimes “q if p.” Statement p is called the premise of the implication and q is called the conclusion.

Because conditional statements play such an essential role in mathematical reasoning, a
variety of terminology is used to express pq. You will encounter most if not all of the following ways to express this conditional statement:

  1. “if p, then q
  2. p implies q
  3. “if p, q
  4. p only if q
  5. p is sufficient for q
  6. “a sufficient condition for q is p
  7. q if p
  8. q whenever p
  9. q when p
  10. q is necessary for p
  11. “a necessary condition for p is q
  12. q follows from p
  13. q unless ¬p

A useful way to understand the truth value of a conditional statement is to think of an
obligation or a contract. For example, the pledge many politicians make when running for office is “If I am elected, then I will lower taxes.

Example 1. Each of the following statements is an implication:

  1. If you score 85% or above in this class, then you will get an A.
  2. If the U.S. discovers that the Taliban Government is involved in the terrorist attack, then it will retaliate against Afghanistan.
  3. My thumb will hurt if I hit it with a hammer.
  4. x = 2 implies x + 1 = 3.

You can view Statement 1 above as a promise. It says You are guaranteed an A provided you score 85% or above. Suppose you score a 90% in the class. If your final grade is an
A, then the promise was kept and Statement 1 is true. If your grade is not an A, then the promise was broken and Statement 1 is false. But what if you do not score 85% or above? Is Statement 1 true or false in this case? Statement 1 does not say what grade you will receive if you score less than 85%. If you score 75% in the class and receive a B, you cannot complain that the promise was broken. If you score 84% and end up with an A, you still cannot say that the promise was broken. When the premise p of the implication “p implies q” is false, we are forced into a corner. We cannot say that the implication is false, yet we have no evidence that it is true—because p didn’t happen.

This situation is reminiscent of the following dialogue from the Three Stooges:

Larry: I couldn’t say ‘yes’ and I couldn’t say ‘no’.
Curly: Could you say ‘maybe’?
Larry: I might.
Moe: [Hits them both on the head.]

Logicians have decided to take an “innocent until proven guilty” stance on this issue. An if—then statement is considered true until proven false. Since we cannot call the statement p implies q false when p is false, our only alternative is to call it true. So the chart for implies is:

The if—then Chart:
p     q      p implies q
T      T           T
T      F          F
F      T          T
F      F          T
We emphasize again the surprising fact that a false statement implies anything.

Example 2

  1.  Does 2 = 3 imply 2 + 1 = 3 + 1?
    Yes, it’s an example of the rule x = y implies x + 1 = y + 1.
  2.  Does 2 = 3 imply 2 · 0 = 3 · 0?
    Yes, it’s an example of the rule x = y implies xz = yz.

Example 3. Consider the following implications

  1. If elephants can fly, then the Cubs will win the World Series this year.
  2. If elephants can fly, then the Cubs will lose the World Series this year.

Both statements are true—assuming, of course, that elephants can’t fly.

Warning to die hard Cubs fans: please do not take Statement 1 too seriously and push elephants out of trees, hoping that one might fly.

Example 4. Consider the following implications

  1. If Hydrochloric acid (HCl) and Sodium Hydroxide (NaOH) are combined, then table salt (NaCl) will be produced.
  2. If March has 31 days, then dogs are mammals.

Both statements are true. The first statement is an example of cause and effect and reflects the chemical equation HCl + NaOH = NaCl + H2O.
In the second statement, there is clearly no causal relation between days of the month and dogs being mammals. Both the premise and the conclusion of Statement 2 are true, so according to the chart, the implication is true.

The point here is that the use of implies in logic is very different from its use in everyday language to reflect causality. From the chart we see that the implication if p then q is false when it happens that p is true, but q is false. This leads us to the surprising conclusion that the negation of an implication is an and statement. The negation of the statement p implies q is the statement p and not q.

Example 5.

  1. The negation of “if I hit my thumb with a hammer, then my thumb will hurt” is “I hit my thumb with a hammer and my thumb does not hurt”.
  2. The negation of “if Sosa is traded, then Cubs attendance will drop” is “Sosa is traded and the Cubs attendance does not drop”.

 

Example 6. The Four Card Problem

You are shown one side of four cards. You are told that each card has a number on one side and a letter on the other side. You are to test the rule:

if a card has a vowel on one side, then it has an even number on the other side. You want to find out whether the rule is true or false. What are the only cards you need to turn over to test the rule (and why) if the cards pictured in front of you are:
E K 4 7
[The answer is given at the end of this section.]

The converse of the statement p implies q is the statement q implies p.

Example 7.

The converse of “if an elephant walks in Mom’s garden, then her tomato plants will be ruined” is “if Mom’s tomato plants are ruined, then an elephant was walking in her garden“.

It is clear from this example that a statement is not logically equivalent to its converse. There could be other causes for ruined tomato plants besides promenading pachyderms. The inverse of the statement p implies q is the statement not p implies not q. The contrapositive of the statement p implies q is the statement not q implies not p.

 

Example 8.
Statement: If the gloves fit, then the jury will acquit.
Converse: If the jury acquits, then the gloves fit.
Inverse: If the gloves don’t fit, then the jury won’t acquit.
Contrapositive: If the jury doesn’t acquit, then the gloves don’t fit.

It can be shown by using truth charts that a statement is logically equivalent to its contrapositive and the converse is logically equivalent to the inverse.

Example 9. The statement “if I hit my thumb with a hammer, then my thumb will hurt” is logically equivalent to “if my thumb doesn’t hurt, then I didn’t hit is with a hammer“.

 

Example 10. Stated as an if–then sentence, the Golden Rule becomes “if you want other people to act in a certain way to you, then you should act that way towards them”. The inverse of the Golden Rule is “if you don’t want other people to act in a certain way to you, then you should not act that way towards them”.

Many people consider the inverse (or equivalently, the converse) of the Golden Rule to be a more reasonable moral law. The biconditional statement p if and only if q means that both p and q are true or else they are both false.

The if and only if Chart:

p      q      p if and only if q
T      T          T
T      F          F
F      T          F
F      F          T

The biconditional p if and only if q is logically equivalent to saying p implies q and q implies p.

Example 11. You are eligible to vote in a United States election if and only if you are a United States citizen, 18 years or older, and not a convicted felon.

 

The answer to the four-card problem is: you only need to turn over cards ‘E’ and ‘7’.

Beginners guide to creating a REST API

If you’re reading this, you’ve probably heard the terms API and REST thrown around and you’re starting to wonder what the fuss is all about. Maybe you already know a little bit, but don’t know how to get started. In this guide, I will explain the basics of REST and how to get started building an API (including authentication) for your application.

What is an API?

The term API stands for Application Programming Interface. The term can be used to describe the features of a library, or how to interact with it. Your favorite library may have “API Documentation” which documents which functions are available, how you call them, which arguments are required, etc.

However, these days, when people refer to an API they are most likely referring to an HTTP API, which can be a way of sharing application data over the internet. For example, Twitter has an API that allows you to request tweets in a format that makes it easy to import into your own application. This is the true power of HTTP APIs, being able to “mashup” data from multiple applications into your own hybrid application, or create an application which enhances the experience of using someone else’s application.

For example, let’s say we have an application that allows you to view, create, edit, and delete widgets. We could create an HTTP API that allows you to perform these functions:

http://example.com/view_widgets
http://example.com/create_new_widget?name=Widgetizer
http://example.com/update_widget?id=123&name=Foo
http://example.com/delete_widget?id=123

A problem has started to arise when everyone starts implementing their own APIs. Without a standard way of naming URLs, you always have to refer to the documentation to understand how the API works. One API might have a URL like /view_widgets whereas another API might use /widgets/all.

Don’t worry, REST comes to rescue us from this mess.

What is REST?

REST stands for Representational State Transfer. This is a term invented by Roy Fielding to describe a standard way of creating HTTP APIs. He noticed that the four common actions (view, create, edit, and delete) map directly to HTTP verbs that are already implemented: GETPOSTPUTDELETE.

If you’re new to HTTP, you may not be familiar with some of these verbs. So let me give a brief rundown on HTTP methods.

HTTP methods

There are technically 8 different HTTP methods:

GET
POST
PUT
DELETE
OPTIONS
HEAD
TRACE
CONNECT

Most of the time, when you’re clicking around in your browser, you are only ever using the GET HTTP method. GET is used when you are “getting” a resource from the internet. When you submit a form, you are usually using the POST method to “post data” back to the website. As for the other methods, some browsers don’t even implement them all. However, for our uses, that doesn’t matter. What matters is that we have a bunch of “verbs” to choose from which help to describe the actions we are taking. We will be using client libraries which already know how to use the different HTTP methods.

Examples of REST

Let’s look at a few examples of what makes an API “RESTful”. Using our widgets example again…

If we wanted to view all widgets, the URL would look like this:

GET http://example.com/widgets

Create a new widget by posting the data:

POST http://example.com/widgets
Data:
    name = Foobar

To view a single widget we “get” it by specifying that widget’s id:

GET http://example.com/widgets/123

Update that widget by “putting” the new data:

PUT http://example.com/widgets/123
Data:
    name = New name
    color = blue

Delete that widget:

DELETE http://example.com/widgets/123

Anatomy of a REST URL

You might have noticed from the previous examples that REST URLs use a consistent naming scheme. When you are interacting with an API, you are almost always manipulating some sort of object. In our examples, this is a Widget. In REST terminology, this is called a Resource. The first part of the URL is always the plural form of the resource:

/widgets

This is always used when referring to this collection of resources (“list all” and “add one” actions). When you are working with a specific resource, you add the ID to the URL.

/widgets/123

This URL is used when you want to “view”, “edit”, or “delete” the particular resource.

Nested Resources

Let’s say our widgets have many users associated with them. What would this URL structure look like?

List all:

GET /widgets/123/users

Add one:

POST /widgets/123/users
Data:
    name = Andrew

Nested resources are perfectly acceptable in URLs. However, it’s not a best practice to go more than two levels deep. It’s not necessary because you can simply refer to those nested resources by ID rather than nesting them within their parents. For example:

/widgets/123/users/456/sports/789

…can be referenced as:

/users/456/sports/789

…or even:

/sports/789

HTTP Status Codes

Another important part of REST is responding with the correct status code for the type of request that was made. If you’re new to HTTP status codes, heres a quick summary. When you make an HTTP request, the server will respond with a code which corresponds to whether or not the request was successful and how the client should proceed. There are four different levels of codes:

  • 2xx = Success
  • 3xx = Redirect
  • 4xx = User error
  • 5xx = Server error

Here’s a list of the most important status codes:

Success codes:

  • 200 – OK (the default)
  • 201 – Created
  • 202 – Accepted (often used for delete requests)

User error codes:

  • 400 – Bad Request (generic user error/bad data)
  • 401 – Unauthorized (this area requires you to log in)
  • 404 – Not Found (bad URL)
  • 405 – Method Not Allowed (wrong HTTP method)
  • 409 – Conflict (i.e. trying to create the same resource with a PUT request)

API response formats

When you make an HTTP request, you can request the format that you want to receive. For example, making a request for a webpage, you want the format to be in HTML, or if you are downloading an image, the format returned should be an image. However, it’s the server’s responsibility to respond in the format that was requested.

JSON has quickly become the format of choice for REST APIs. It has a lightweight, readable syntax that can be easily manipulated. So when a user of our API makes a request and specifies JSON as the format they would prefer:

GET /widgets
Accept: application/json

…our API will return an array of widgets formatted as JSON:

[
  {
    id: 123,
    name: 'Simple Widget'
  },
  {
    id: 456,
    name: 'My other widget'
  }
]

If the user requests a format that we haven’t implemented, what do we do? You can throw some type of error, but I would recommend enforcing JSON as your standard response format. It’s the format that your developers will want to use. No reason to support other formats unless you already have an API which needs to be supported.

Building a REST API

Actually building a REST API is mostly outside the scope of this tutorial since it is language specific, but I will give a brief example in Ruby using a library called Sinatra:

require 'sinatra'
require 'JSON'
require 'widget' # our imaginary widget model

# list all
get '/widgets' do
  Widget.all.to_json
end

# view one
get '/widgets/:id' do
  widget = Widget.find(params[:id])
  return status 404 if widget.nil?
  widget.to_json
end

# create
post '/widgets' do
  widget = Widget.new(params['widget'])
  widget.save
  status 201
end

# update
put '/widgets/:id' do
  widget = Widget.find(params[:id])
  return status 404 if widget.nil?
  widget.update(params[:widget])
  widget.save
  status 202
end

delete '/widgets/:id' do
  widget = Widget.find(params[:id])
  return status 404 if widget.nil?
  widget.delete
  status 202
end

API authentication

In normal web applications, handling authentication is usually handled by accepting a username and password, and saving the user ID in the session. The user’s browser saves a cookie with ID of the session. When the user visits a page on the site that requires authentication, the browser sends the cookie, the app looks up the session by the ID (if it hasn’t expired), and since the user ID was saved in the session, the user is allowed to view the page.

With an API, using sessions to keep track of users is not necessarily the best approach. Sometimes, your users may want to access the API directly, other times the user may way to authorize another application to access the API on their behalf.

The solution to this is to use token based authentication. The user logs in with their username and password and the application responds with a unique token that the user can use for future requests. This token can be passed onto the application so that the user can revoke that token later if they choose to deny that application further access.

There is a standard way of doing this that has become very popular. It’s called OAuth. Specifically, version 2 of the OAuth standard. There are a lot of great resources online for implementing OAuth so I would say that is outside the scope of this tutorial. If you are using Ruby, there are some great libraries that handle most of the work for you, like OmniAuth.

Hopefully, I’ve filled in enough blanks for you to get started. If you still have questions, you may find this tutorialhelpful.

Source: https://www.andrewhavens.com/posts/20/beginners-guide-to-creating-a-rest-api