Ex.
C++. #include <iostream> // Fibonacci numbers, imperative style int fibonacci(int iterations) { int first = 0, second = 1; // seed values for (int i = 0; i < iterations; ++i) { int sum = first + second; first = second; second = sum; } return first; } int main() { std::cout << fibonacci(10) << "\n"; return 0; }
A functional version (in Haskell) has a different feel to it: -- Fibonacci numbers, functional style -- describe an infinite list based on the recurrence relation for Fibonacci numbers fibRecurrence first second = first : fibRecurrence second (first + second) -- describe fibonacci list as fibRecurrence with initial values 0 and 1 fibonacci = fibRecurrence 0 1 -- describe action to print the 10th element of the fibonacci list main = print (fibonacci !!
Logic Programming ------------------------------------------------- {-
-------------------------------------------------
Problem:
-------------------------------------------------
------------------------------------------------- There is a tribe where all the Male members speak true statements and Female
-------------------------------------------------
members never speak two true statements in a row, nor two untrue statements in
-------------------------------------------------
a row. (I apologize for the obvious misogyny).
-------------------------------------------------
------------------------------------------------- A researcher comes across a mother, a father, and their child. The mother and
-------------------------------------------------
father speak English but the child does not. However, the researcher asks the
-------------------------------------------------
child "Are you a boy?". The child responds but the researcher doesn't
-------------------------------------------------
understand the response and turns to the parents for a translation.
-------------------------------------------------
------------------------------------------------- Parent 1: "The child said 'I am a boy.'"
-------------------------------------------------
Parent 2: "The child is a girl. The child lied."
-------------------------------------------------
------------------------------------------------- What is the sex of parent 1, parent 2, the child, and what sex did the child
-------------------------------------------------
say they were?
-------------------------------------------------
------------------------------------------------- Bonus:
-------------------------------------------------
------------------------------------------------- There is a unique solution for heterosexual, gay, and lesbian couples. Find
-------------------------------------------------
all three solutions.
-------------------------------------------------
------------------------------------------------- Solution:
-------------------------------------------------
------------------------------------------------- Run the code :)
-------------------------------------------------
------------------------------------------------- Approach:
-------------------------------------------------
------------------------------------------------- Use the monadic properties of lists to setup some basic logic programming.
-------------------------------------------------
There are four variables in the puzzle: Sex of parent 1, Sex of parent 2, Sex
-------------------------------------------------
of the child, and the Sex the child said they were. Each of these has two
-------------------------------------------------
possibilities, which means we've got 2^4 == 16 possible outcomes.
-------------------------------------------------
------------------------------------------------- Using List Monads we can realize all 2^4 outcomes in a straightforward
-------------------------------------------------
fashion. Then it is just a matter of testing each combination to make sure it
-------------------------------------------------
fits the constraints of the puzzle.
-------------------------------------------------
------------------------------------------------- We have two axioms:
-------------------------------------------------
------------------------------------------------- 1. A Male does not lie.
-------------------------------------------------
2. A Female will never tell two lies or two truths in a row.
-------------------------------------------------
------------------------------------------------- And we have three statements (i.e. logical expressions) in the puzzle:
-------------------------------------------------
------------------------------------------------- 1. The child said a single statement, in which they declared their sex.
-------------------------------------------------
2. Parent 1 said a single statement: "The child said 'I am a a boy'"
-------------------------------------------------
3. Parent 2 said two statements: "The child is a girl. The child lied."
-------------------------------------------------
------------------------------------------------- Each of those three statements is realized as a function. These functions do
-------------------------------------------------
not test the truth of the statement but rather test its logical validity in
-------------------------------------------------
the face of the axioms.
-------------------------------------------------
------------------------------------------------- For example, if the Child is Male then it is not possible the child said they
-------------------------------------------------
were Female since that would violate axiom 1. Similarly if the Child is Female
-------------------------------------------------
then no matter if they lied or told the truth the statement is valid in the
-------------------------------------------------
face of the axioms, this is an example of the truth of statement differing
-------------------------------------------------
from its logical validity.
-------------------------------------------------
------------------------------------------------- -}
-------------------------------------------------
------------------------------------------------- -- People are either Male or Female, this represents the constraints of the puzzle.
-------------------------------------------------
data Sex = Male | Female deriving (Eq, Show)
-------------------------------------------------
------------------------------------------------- -- When creating an answer we stuff it into this data structure
-------------------------------------------------
data PuzzleAnswer = PuzzleAnswer {
-------------------------------------------------
parent1 :: Sex,
-------------------------------------------------
parent2 :: Sex,
-------------------------------------------------
child :: Sex,
-------------------------------------------------
child_desc :: Sex
-------------------------------------------------
}
-------------------------------------------------
------------------------------------------------- -- This lets us print out the data structure in a friendly way
-------------------------------------------------
instance Show (PuzzleAnswer) where
-------------------------------------------------
show pa = "Parent1 is " ++ (show $ parent1 pa) ++ "\n" ++
-------------------------------------------------
"Parent2 is " ++ (show $ parent2 pa) ++ "\n" ++
-------------------------------------------------
"The child is " ++ (show $ child pa) ++ "\n" ++
-------------------------------------------------
"The child said they were " ++ (show $ child_desc pa) ++ "\n"
-------------------------------------------------
------------------------------------------------- {-
-------------------------------------------------
childs_statement_is_valid(child_sex, child_described_sex)
-------------------------------------------------
------------------------------------------------- The only combination that violates the axioms is (Male, Female) since a Male
-------------------------------------------------
does not lie. Obviously (Male, Male) and (Female, *) are valid statements.
-------------------------------------------------
-}
-------------------------------------------------
childs_statement_is_valid :: Sex -> Sex -> Bool
-------------------------------------------------
childs_statement_is_valid Male Female = False
-------------------------------------------------
childs_statement_is_valid _ _ = True
-------------------------------------------------
------------------------------------------------- {-
-------------------------------------------------
parent1_statement_is_valid(parent1_sex, child_described_sex)
-------------------------------------------------
------------------------------------------------- Parent 1 said "The child said 'I am a boy'". The only invalid combination is
-------------------------------------------------
(Male, Female), because that'd imply a Male (the parent) lied. Obviously
-------------------------------------------------
(Male, Male) is okay because then parent 1 is telling the truth. (Female, *)
-------------------------------------------------
is dubious because you can't trust a Female.
-------------------------------------------------
-}
-------------------------------------------------
parent1_statement_is_valid :: Sex -> Sex -> Bool
-------------------------------------------------
parent1_statement_is_valid Male Female = False
-------------------------------------------------
parent1_statement_is_valid _ _ = True
-------------------------------------------------
------------------------------------------------- {-
-------------------------------------------------
parent2_statement_is_valid(parent1_sex, child_sex, child_described_sex)
-------------------------------------------------
------------------------------------------------- Parent 2 said "The child is a girl. The child lied." If Parent 2 is Male
-------------------------------------------------
then the only way this can be a legal statement is if the chlid is Female and
-------------------------------------------------
said they were Male. This would mean the child is in fact a girl and the
-------------------------------------------------
child did in fact lie, two statements which are both true. This corresponds
-------------------------------------------------
to (Male, Female, Male) being legal.
-------------------------------------------------
------------------------------------------------- If Parent2 is Female then (Female, *, Female) are both true. (Female, Male,
-------------------------------------------------
Female) is true because the first statement is false (the child is a girl) but
-------------------------------------------------
the second one is true (the child lied -- it said Female when it was Male).
-------------------------------------------------
(Female, Female, Female) is also legal since the first statement (the child is
-------------------------------------------------
a girl) is true but the second one is a lie (the child lied -- the child said
-------------------------------------------------
they were Female and they are Female).
-------------------------------------------------
------------------------------------------------- Any other combination will be illegal.
-------------------------------------------------
-}
-------------------------------------------------
parent2_statement_is_valid :: Sex -> Sex -> Sex -> Bool
-------------------------------------------------
parent2_statement_is_valid Male Female Male = True
-------------------------------------------------
parent2_statement_is_valid Female _ Female = True
-------------------------------------------------
parent2_statement_is_valid _ _ _ = False
-------------------------------------------------
------------------------------------------------- {-
-------------------------------------------------
Here we use the List Monad to declare the four variables, each ranging over
-------------------------------------------------
the set [Male, Female]. The List Monad transparently constructs all 2^4
-------------------------------------------------
possibilities. The guard statements discard statements that are invalid. We
-------------------------------------------------
have four guards, the three described above and an additional guard that
-------------------------------------------------
asserts the parents are not the same sex.
-------------------------------------------------
------------------------------------------------- The result is a list of tuples listing all possible solutions. There happens
-------------------------------------------------
to be only one, if there was more than one than the other legal ones would be
-------------------------------------------------
returned too.
-------------------------------------------------
-}
-------------------------------------------------
solve_puzzle :: (Sex -> Sex -> Bool) -> [PuzzleAnswer]
-------------------------------------------------
solve_puzzle sexuality_pred = do
-------------------------------------------------
parent1 <- [Male, Female]
-------------------------------------------------
parent2 <- [Male, Female]
-------------------------------------------------
child <- [Male, Female]
-------------------------------------------------
child_desc <- [Male, Female]
-------------------------------------------------
guard $ sexuality_pred parent1 parent2
-------------------------------------------------
guard $ childs_statement_is_valid child child_desc
-------------------------------------------------
guard $ parent1_statement_is_valid parent1 child_desc
-------------------------------------------------
guard $ parent2_statement_is_valid parent2 child child_desc
-------------------------------------------------
return $ PuzzleAnswer {
-------------------------------------------------
parent1=parent1,
-------------------------------------------------
parent2=parent2,
-------------------------------------------------
child=child,
-------------------------------------------------
child_desc=child_desc
-------------------------------------------------
}
-------------------------------------------------
------------------------------------------------- -- Run the program. We use mapM because we're applying a print in Monadic
-------------------------------------------------
-- setting. We use any kind of map because it's possible (due to poor coding)
-------------------------------------------------
-- that the solution could have more than one answer.
-------------------------------------------------
main = do
-------------------------------------------------
putStrLn "----------- Hetrosexual Couple -----------"
-------------------------------------------------
mapM_ print (solve_puzzle (/=))
-------------------------------------------------
putStrLn "----------- Gay Couple -----------"
-------------------------------------------------
mapM_ print (solve_puzzle (\x y -> x == y && x == Male))
-------------------------------------------------
putStrLn "----------- Lesbian Couple -----------"
-------------------------------------------------
mapM_ print (solve_puzzle (\x y -> x == y && x == Female))
You May Also Find These Documents Helpful
-
* Lines 12 and 13 ask the user for the next participants age and gets the next…
- 313 Words
- 2 Pages
Satisfactory Essays -
A nuclear weapon is a weapon that gets it’s destructive power by turning matter into energy. All nuclear weapons are explosives(usually missiles).They can be transported by missiles, bombs,tank shells,mines, or torpedoes. The most destructive nuclear weapons are far more poweful than any conventional(non nuclear) weapon. A nuclear weapon used in a large city could kill millions of people. A large nuclear war could devastate the Earth’s climate and ability to support life(a.k.a nuclear winter).…
- 74 Words
- 1 Page
Satisfactory Essays -
What is the value inside the "value" variable at the end of the given code snippet?…
- 2831 Words
- 12 Pages
Good Essays -
According to my data no my hypothesis was not correct because the number of candies removed after each shaking…
- 348 Words
- 2 Pages
Satisfactory Essays -
4. International Covenant on Civil and Political Rights. http://www.ohchr.org/en/professionalinterest/pages/ccpr.aspx. 23 Mar. 1976. Web. 10 Dec. 2013.…
- 1539 Words
- 7 Pages
Good Essays -
This unit deals with Arms Race and the Nuclear Threat in the present day world. After…
- 7055 Words
- 29 Pages
Powerful Essays -
At this time in our world we live in I do believe nuclear terrorism is a huge threat and the U.S. should be very concerned about it. It was noted by Jeffrey T. Richelson that “declassified documents have confirmed that the U.S. (and other) governments have anticipated the possibility of a terrorist nuclear incident at such high-profile events as the 2009 inauguration of President Barack Obama and the 2010 Vancouver Olympics” (Richelson 2012). United States government officials have been concerned with the possibility of a terrorist attack since the attacks on the world trade center in 2001. Another concern of the United States is the possibility of nuclear capable Iran might produce either weapons, weapons-grade material for dirty bombs, or supply technical knowledge to its Shi'a allies in Hezbollah. It was recently reported by CNN news center that a terrorist attack in Canada had been stopped and the cell came from Iran who was secretly harboring members of Al Qaida. I do not believe these types of countries should have nuclear capabilities. Another concern is the possibilities of nuclear materials being stolen and not being able to track them down.…
- 477 Words
- 2 Pages
Good Essays -
Nuclear terrorism denotes the detonation of a yield-producing nuclear bomb containing fissile material by terrorists.[1] Some definitions of nuclear terrorism include the sabotage of a nuclear facility and/or the detonation of a radiological device, colloquially termed a dirty bomb, but consensus is lacking. In legal terms, nuclear terrorism is an offense committed if a person unlawfully and intentionally “uses in any way radioactive material … with the intent to cause death or serious bodily injury; or with the intent to cause substantial damage to property or to the environment; or with the intent to compel a natural or legal person, an international organization or a State to do or refrain from doing an act”, according to the 2005 United Nations International Convention for the Suppression of Acts of Nuclear Terrorism.…
- 1746 Words
- 6 Pages
Powerful Essays -
This event is in the news because a country violated a law that the entire world agreed on not doing anymore. India have always wanted to become nuclear, and their wish came true. They accepted their consequences of being nuclear, but they are happy. It's neighboring country Pakistan and India have had two wars, and always competed to be the best, and so far India is winning, because India have about 65 warheads and Pakistan have about 25 warheads. India have also declared they have nuclear capability were as Pakistan have not. India is exceptionally proud of having nuclear power, after conducting their first test in 1976, and then five in the year 1998. India have always wanted to be known for something to do with military and now they have accomplished that goal.<br><br>Proposals have been suggested for this problem, but only two countries have sort of resolved the problem. Japan and America have put sanctions on India. Japan have froze all bank access to India from their banks, but trade is still continuing. America its most dependent country have put money sanctions on India, in which now it will now effect India's economy. India is 14.5 billion dollars in debut. If I could have a chance to resolve this problem, I would let them keep there nuclear power, but would have to lay down some rules on what they can't do and what they can do. I would not allow anymore nuclear test's. I would also make it mandatory that the bombs have to reach a certain requirement.<br><br>India's past prime ministers have been scared of becoming nuclear, but it has been the India's citizens dream to become nuclear, and now there dream has become a reality. In recent news of India, their economy is dropping rapidly, and is making no attempt to rise. There is only one problem with nukes they hold. There nukes, Russia's, China's, Frances all are short range nukes, which go about 5000 miles. The only two countries that it's nukes can mostly reach any were in the world is the United…
- 368 Words
- 2 Pages
Satisfactory Essays -
Nuclear Proliferation CURRENT BUSINESS AFFAIRS Govt. College of Science Presented to [Sir Muhammad Adil] Presented by [AR SHAKIR] BBA 6th Semester Roll No: 1768 (54) Table of Contents Table of Contents History ________________________________________________________________ 1 Origins _______________________________________________________________ 1 Early Years ___________________________________________________________ 1 Developments _________________________________________________________ 2 Nuclear Proliferation ___________________________________________________…
- 8122 Words
- 49 Pages
Powerful Essays -
Rather than use militarization or be tough on iran which would encourage a hostile relationship, the U.S. should approach Iran’s nuclear ambitions by talking to Iranian leaders and persuade them that developing nuclear weapons would not be the best thing for iran’s national interests. Rather than leading to stabilization and the mad situation, it would probably lead to political coercion which would tempt other neighboring Arab countries to proliferate as well and would highlight rivalries, particularly with Israel. The U.S. needs to speak to Iranian experts, scholars, and officials to explain to them the negative implications of iran possessing nuclear weapons. I personally do not think that the u.S. should reverse Iranian ambitions or to stage a regime change. The us needs to “engage Iran diplomatically” and use a policy of carrots and sticks where…
- 496 Words
- 2 Pages
Good Essays -
Just after the signing ceremony in Geneva on Sunday, President Hassan Rouhani of Iran declared that the world had recognized his country’s “nuclear rights.” He was right. The deal will only lead Iran to be more stubborn.…
- 403 Words
- 2 Pages
Good Essays -
A nuclear explosion is caused by the release of energy in an atom, either through fission or fusion. Fission weapons cause an explosion by the splitting of atomic nuclei. This happens when a neutron collides with the nucleus of an atom. The protons in the nucleus are transformed into a great amount of energy and two or three more neutrons are sent out, which go on to split other nuclei. If this continues, a chain reaction will occur. The result is a gigantic explosion. To form a chain reaction, a certain amount of material is needed. This amount is known as the critical mass. If the amount is too small it is called a subcritical mass. The critical mass of a material depends on its purity. The materials used in making fission weapons are uranium and plutonium. They are the only elements able to be used in making a fission weapon.…
- 680 Words
- 3 Pages
Good Essays -
The atomic bombs dropped on Hiroshima and Nagasaki at the end of the second world war wiped out the entire place leaving it without any form of existence. This incident changed the history of war completely. For miles and miles the atmosphere was polluted and people had faced the radioactive rays. These rays proved to be very harmful to the upcoming generations. Children were born with all sorts of disabilities , diseases and defects. The effects were horrendous on millions of innocent civilians.…
- 670 Words
- 3 Pages
Good Essays