# Cognitive Psychology and Cognitive Neuroscience/Present and Future of Research

+:------------------------------+:----:+------------------------------:+
| Previous                     | [O   | *Next Chapter*                |
| Chapter | niti |                               |
|                               | ve_P |                               |
|                               | sych |                               |
|                               | olog |                               |
|                               | y_an |                               |
|                               | d_Co |                               |
|                               | gnit |                               |
|                               | ive_ |                               |
|                               | Neur |                               |
|                               | osci |                               |
|                               | ence |                               |
|                               |  "wi |                               |
|                               | kili |                               |
|                               | nk") |                               |
+-------------------------------+------+-------------------------------+

about the future.\"* Robert Storm Petersen

## Introduction / Until now

Developing from the information processing approach, present cognitive
psychology differs from classical psychological approaches in the
methods used as well as in the interdisciplinary connections to other
sciences. Apart from rejecting introspection as a valid method to
analyse mental phenomena, cognitive psychology introduces further,
mainly computer-based, techniques which have not been in the range of
classical psychology by now.

By using brain-imaging-techniques like fMRI, cognitive psychology is
able to analyse the relation between the physiology of the brain and
mental processes. In the future, cognitive psychology will likely focus
on computer-based methods even more. Thus, the field will profit from
improvements in the area of IT. For example, contemporary fMRI scans are
plagued by many possible sources of error, which should be solved in the
future, thereby improving the power and precision of the technique. In
addition, computational approaches can be combined with classical
behavioural approaches, where one infers a participant\'s mental states
from exhibited behaviour.

Cognitive psychology, however, does not only rely on methods developed
by other branches of science. It also collaborates with closely related
fields, including artificial intelligence, neuroscience, linguistics and
the philosophy of mind. The advantage of this multidisciplinary approach
is clear: different perspectives on the topic make it possible to test
hypotheses using different techniques and to eventually develop new
conceptual frameworks for thinking about the mind. Often, modern studies
of cognitive psychology criticise classical information processing
approaches, which opens the door for other approaches to acquire
additional importance. For example, the classical approach has been
modified to a parallel information processing approach, which is thought
to be closer to the actual functioning of the brain.

## Today\'s approaches

### The momentary usage of brain imaging

How are the known brain imaging methods used? What kind of information
can be derived using this methods?

#### fMRI

fMRI is an non-invasive imaging method that pictures active structures
of the brain in a high spatial resolution. For that the participant has
to lie in a tube and his brain is pictured. While doing a task active
structures in the brain of the participant can be recognised on the
recordings.

**How?**\
If parts of the brain are active, the metabolism is also stimulated. The
blood, that has an important function in the metabolic transport is
flowing to the active nerve cells. The haemoglobin in the red blood
cells carries oxygen (oxyhaemogliobin) when flowing to the part that is
active and that needs oxygen, to consume and work. With consumption the
haemoglobin „delivers" the oxygen (desoxyhaemoglobin). This leads to
local changes in the relative concentration of oxyhemoglobin and
desoxyhemoglobin and changes in local blood volume and blood flow. While
haemoglobin is oxygenated it is diamagnetic (meaning the material tends
to leave the magnetic field), but paramagnetic (material tends to
migrate into the magnetic field) while desoxygenated. The magnetic
resonance signal of blood is therefore slightly different depending on
the level of oxygenation.

By being able to detect the magnetic properties mentioned above, the
fMRI-scanner is able to determine alterations in blood flow and blood
volume, and construct a picture. This picture shows the brain and its
activated parts. While the participant is doing a task the researcher
can derive, which brain regions are involved. This is an indirect
measure, as the metabolism is measured and not the neuronal activity
itself. Furthermore this imaging method has good spatial
resolution(where the activity occurs) but low temporal resolution (when
the activity occurs), as measurements occur after the neuronal activity.

#### EEG

The Electroencephalogram (EEG) is another non-invasive brain imaging
method. Electronic signals from the human brain are recorded while the
participant is doing a task. The electronic activity of the neuronal
cells, that is adding can be measured.

The electronic activity is measured by attaching electrodes to the skin
of the head. In most cases the electrodes are installed on a cap, that
the participant wears. It is very time-consuming to install the cap
correctly on the head of the participant, but it is very important for
the outcome, that everything is in the right place. To assure the adding
of the signals the electrodes have to be installed geometric and in a
parallel configuration. This technique is applied to measure the
event-related potential (ERP), potential changes. They are correlated
temporal to an emotional, sensoric, cognitive or motoric event. In the
experiment a certain event has to be repeated again and again. The type
ERP then can be extracted and calculated. This method is not only
time-consumptive, also a lot of disrupting factors complicate the
measuring. Moreover this method has a very high temporal resolution, but
a very low spatial resolution. It is hardly possible to measure activity
in deeper brain regions or to detect the source of the activity
interpreting only the recordings.

### Interdisciplinary Approaches

#### Cognitive Science

Cognitive science is multidisciplinary science. It comprises areas of
cognitive psychology, linguistics, neuroscience, artificial
intelligence, cognitive anthropology, computer science and philosophy.
Cognitive science concentrates to study the intelligent behaviour of
humans, which includes perception, learning, memory, thought and
language. Research in cognitive sciences are based on naturalistic
research methods such as cognitive neuropsychology, introspection,
psychological experimentation, mathematical modelling and philosophical
argumentation.

In the beginning of the cognitive sciences the most common method was
introspection. It meant that the test subject evaluated his or her own
cognitive thinking. In these experiments the researchers were using
experienced subjects because they had to analyse and report their own
cognitive thinking. Problems can occur when the results are interpreted
and the subject has different reports from the same action. Obviously a
clear separation is needed between the matters that can be studied by
introspection and the ones that are not adequate for this method.

Computational modelling in cognitive science means that the mind is seen
as a machine. This approach seeks to express theoretical ideas through
computational modelling that generate behaviour similar to humans.
Mathematical modelling is based on flow charts. The model\'s quality is
very important to ensure the equivalence of the input and results.

Nowadays the researchers in cognitive sciences use often theoretical and
computational models. \"This does not exclude their primary method of
experimentation with human participants. In cognitive sciences it is
also important to bring the theories and the experimenting together.
Because it comprises so many fields of science it is important to bring
together the most appropriate methods from all these fields. The
psychological experiments should be interpreted through a theory that
expresses mental representations and procedures. The most productive and
revealing way to perform research in cognitive sciences is to combine
different approaches and methods together. This ensures overall picture
from the research area and it comprises the viewpoints of all the
different fields.\" (Thagard, Cognitive Science) Nevertheless Cognitive
Science has not yet managed to succeed in bringing the different areas
together. Nowadays it is criticised for not establishing a science on
its own. Rather few scientist really address themselves as cognitive
scientists. Furthermore the basic metaphor of the brain functioning like
a computer is challenged as well as the distinctions between their
models and nature (cf. Eysenck & Keane, Cognitive Psychology, pp.
519-520). This of course brings up a lot of work for the future.
Cognitive Science has to work on better models that explain natural
processes and that are reliably able to make predictions. Furthermore
these models have to combine multiple mental phenomena. In addition to
that a general \"methodology for relating a computational model\'s
behaviour to human behaviour\" has to be worked out. Hereby the strength
of such models can be increased. Apart from that Cognitive Science needs
to establish an identity with prominent researchers that avow themselves
to Cognitive Science. And finally its biggest goal, the creation of a
general unifying theory of human cognition (see Theory Part), has to be
reached (cf. ibid, p. 520).

##### Experimental Cognitive Psychology

Psychological experimentation studies mental functions. This is done
with indirect methods meaning reasoning. These studies are performed to
find causal relations and the factors influencing behaviour. The
researcher observes visible actions and makes conclusions based on these
observations. Variables are changed one at a time and the effect of this
change is being observed. The benefits of experimental researching are
that the manipulated factors can be altered in nearly any way the
researcher wants. From this point it is finally possible to find causal
relations.

In being the classical approach within the field of cognitive
psychology, experimental studies have been the basis for the development
of numerous modern approaches within contemporary Cognitive Psychology.
Its empirical methods have been developed and verified over time and the
gained results were a foundation for many enhancements contributed to
the field of psychology.

Taking into consideration the established character of experimental
cognitive psychology, one might think that methodological changes are
rather negligible. But recent years came up with a discussion concerning
the question, whether the results of experimental CP remain valid in the
"real world" at all. A major objection is that the artificial
environment in an experiment might cause that certain facts and
coherences are unintentionally ignored, which is due to the fact that
for reasons of clarity numerous factors are suppressed (cf. Eysenck &
Keane, Cognitive Psychology, pp. 514--515). A possible example for this
is the research concerning attention. Since the attention of the
participant is mainly governed by the experimenter's instructions, its
focus is basically determined. Therefore \"relatively little is known of
the factors that normally influence the focus of attention\" (ibid, p.
514). Furthermore it turns out to be problematic that mental phenomena
are often examined in isolation. While trying to make the experimental
setup as concise as possible (in order to get clearly interpretable
results) one decouples the aspect at issue from adjacent and interacting
mental processes. This leads to the problem that the results turn out to
be valid in the idealised experimental setting only but not in "real
life". Here multiple mental phenomena interact with each other and
numerous outer stimuli influence the behaviour of mental processes. The
validity gained by such studies could only be characterised as an
internal validity (which means that the results are valid in the special
circumstances created by the experimenter) but not as an external
validity (which means that the results stay valid in changed and more
realistic circumstances) (cf. ibid, p. 514). These objections lead to
experiments which have been developed to refer closer to \"real life\".
According to these experiments \"real-world\" phenomena like
\'absent-mindedness\', \'everyday memory\' or \'reading\' gain
importance. Nevertheless the discussion remains whether such experiments
really deliver new information about mental processes. And whether these
\'everyday phenomenon studies\' really become broadly accepted greatly
depends on the results current experiments will deliver.

Another issue concerning experimental setups in cognitive psychology is
the way individual differences are handled. In general the results from
an experiment are generated by an analysis of variance. This causes that
results which are due to individual differences are averaged out and not
taken into further consideration. Such a procedure seems to be highly
questionable, especially if put into the context of an investigation of
Bowers in 1973, which showed that over 30% of the variance in such
studies are due to individual differences or their interaction with the
current situation (cf. ibid, p. 515). Based on such facts one challenge
for future experimental cognitive psychology is the analysis of
individual differences and finding way to include knowledge about such
differences in general studies.

##### Cognitive Neuroscience

Another approach towards a better understanding of human cognition is
cognitive neuroscience. Cognitive neuroscience lies at the interface
between traditional cognitive psychology and the brain sciences. It is a
science whose approach is characterised by attempts to derive cognitive
level theories from various types of information, such as computational
properties of neural circuits, patterns of behavioural damage as a
result of brain injury or measurements of brain activity during the
execution of cognitive tasks (cf. www.psy.cmu.edu). Cognitive
neuroscience helps to understand how the human brain supports thought,
perception, affection, action, social process and other aspects of
cognition and behaviour, including how such processes develop and change
in the brain over time (cf. www.nsf.gov).

Cognitive neuroscience has emerged in the last decade as an intensely
active and influential discipline, forged from interactions among the
cognitive sciences, neurology, neuroimaging, physiology, neuroscience,
psychiatry, and other fields. New methods for non-invasive functional
neuroimaging of subjects performing psychological tasks have been of
particular importance for this discipline. Non-invasive functional
neuroimaging includes: positron emission tomography (PET), functional
magnetic resonance imaging (fMRI), magnetoencephalography (MEG), optical
imaging (near infra-red spectroscopy or NIRS), anatomical MRI, and
diffusion tensor imaging (DTI) The findings of cognitive neuroscience
are directed towards enabling a basic scientific understanding of a
broad range of issues involving the brain, cognition and behaviour. (cf.
www.nsf.gov).

Cognitive neuroscience becomes a very important approach to understand
human cognition, since results can clarify functional brain
organisation, such as the operations performed by a particular brain
area and the system of distributed, discrete neural areas supporting a
specific cognitive representation. These findings can reveal the effect
on brain organization of individual differences (including even genetic
variation) (cf. www.psy.cmu.edu, www.nsf.gov). Another importance of
cognitive neuroscience is that cognitive neuroscience provides some ways
that allow us to \"obtain detailed information about the brain
structures involved in different kinds of cognitive processing\"
(Eysenck & Keane, Cognitive Psychology, p. 521). Techniques such as MRI
and CAT scans have proved of particular value when used on patients to
discover which brain areas are damaged. Before non-invasive methods of
cognitive neuroscience were developed localisation of \"brain damage
could only be established by post mortem examination\" (ibid). Knowing
which brain areas are related to which cognitive process would surely
lead to obtain a clearer view of brain region, hence, in the end would
help for a better understanding of human cognition processes. Another
strength of cognitive neuroscience is that it serves as a tool to
demonstrate the reality of theoretical distinctions. For example, it has
been argued by many theorists that implicit memory can be divided into
perceptual and conceptual implicit memory; support for that view has
come from PET studies, which show that perceptual and conceptual priming
tasks affected different areas of the brain (cf. ibid, pp. 521-522).
However, cognitive neuroscience is not that perfect to be able to stand
alone and answer all questions dealing with human cognition. Cognitive
neuroscience has some limitations, dealing with data collecting and data
validity. In most neuroimaging studies, data is collected from several
individuals and then averaged. Some concern has arose about such
averaging because of the existence of significant individual
differences. Though the problem was answered by Raichle (1998), who
stated that the differ in individual brain should be appreciated,
however general organising principles emerge that transcend these
differences, a broadly accepted solution to the problem has yet to be
found (cf. ibid, p. 522).

##### Cognitive Neuropsychology

Cognitive Neuropsychology maps the connection between brain functions
and cognitive behaviour. Patients with brain damages have been the most
important source of research in neuropsychology. Neuropsychology also
examines dissociation ("forgetting"), double dissociation and
associations (connection between two things formed by cognition).
Neuropsychology uses technological research methods to create images of
the brain functioning. There are many differences in techniques to scan
the brain. The most common ones are EEG (Electroencephalography), MRI
and fMRI (functional Magnetic Resonance Imaging) and PET (Positron
Emission Tomography).

Cognitive Neuropsychology became very popular since it delivers good
evidence. Theories developed for normal individuals can be verified by
patients with brain damages. Apart from that new theories could have
been established because of the results of neuropsychological
experiments. Nevertheless certain limitations to the approach as it is
today cannot be let out of consideration. First of all the fact that
people having the same mental disability often do not have the same
lesion needs to be pointed out (cf. ibid, pp.516-517). In such cases the
researchers have to be careful with their interpretation. In general it
could only be concluded that all the areas that the patients have
injured could play a role in the mental phenomenon. But not which part
really is decisive. Based on that future experiments in this area tend
to make experiments with a rather small number of people with pretty
similar lesion respectively compare the results from groups with similar
syndromes and different lesions. In addition to that the situation often
turns out to be vice versa. Some patients do have pretty similar lesions
but show rather different behaviour (cf. ibid, p.517). One probable
reason therefore is that the patients differ in their age and lifestyle
(cf. Banich, Neuropsychology, p.55). With better technologies in the
future one will be better able to distinguish the cases in which really
the various personalities make the difference or in which cases the
lesions are not entirely equal. In addition to that the individual brain
structures which may cause the different reactions to the lesions will
become a focus of research. Another problem for Cognitive
Neuropsychology is that their patients are rare. The patients which are
interesting for such research have lesions of an accident or suffered
during war. But in addition there are differences in the manner of the
lesion. Often multiple brain regions are damaged which makes it very
hard to determine which of them is responsible for the examined
phenomenon. The dependency on chance whether there are available
patients will remain in future. Thereby predictions concerning this
aspect of the research are not very reliable. Apart from that it is not
possible yet to localise some mental processes in the brain. Creative
thought or organisational planning are examples (cf. Eysenck & Keane,
Cognitive Psychology, p.517). A possible outcome of the research is that
those activities rely on parallel processing. This would support the
idea of the modification of the information processing theory that will
be discussed later on. But if it shows up that a lot of mental processes
depend on such parallel processing it would turn out to be a big
drawback for Cognitive Psychology since its core is the modularization
of the brain and the according phenomena. In this context the risk of
overestimation and underestimation has to be mentioned. The latter
occurs because Cognitive Psychology often only identifies the most
important brain region for the mental task. Other regions that are
related thereto could be ignored. This could turn out to be fundamental
if really parallel processing is crucial to many mental activities.
Overestimation occurs when fibers that only pass the damaged brain
region are lesioned, too. The researcher concludes that the respective
brain region plays an important role in the phenomenon he analyses even
though only the deliverance of the information passed that region (cf.
ibid). Modern technologies and experiments here have to be developed in
order to provide valid and precise results.

#### Unifying Theories

A unified theory of cognitive science serves the purpose to bring
together all the vantage points one can take toward the brain/mind. If a
theory could be formed which incorporates all the discoveries of the
disciplines mentioned above a full understanding would be tangible.

##### ACT-R

ACT-R is a Cognitive Architecture, an acronym for Adaptive Control of
Thought--Rational. It provides tools which enable us to model the human
cognition. It consists mainly of five components: Perceptual-motor
modules, declarative memory, procedural memory, chunks and buffers. The
declarative memory stores facts in "knowledge-units", the chunks. These
are transmitted through the modules respective buffers, which contain
one chunk at a time. The procedural memory is the only one without an
own buffer, but is able to access the contents of the other buffers. For
example those of the perceptual-motor modules, which are the interface
with the (simulated) outer world. Production is accomplished by
predefined rules, written is LISP. The main character behind it is John
R. Anderson who tributes the inspiration to Allan Newell.

##### SOAR

SOAR is another Cognitive Architecture, an acronym for State, Operator
And Result. It enables one to model complex human capabilities. Its goal
is to create an agent with human-like behaviour. The working principles
are the following: Problem-solving is a search in a problem-space.
Permanent Knowledge is represented by production rules in the production
memory. Temporary Knowledge is represented by objects in the working
memory. New Goals are created only if a dead end is reached. The
learning mechanism is Chunking. Chunking: If SOAR encounters an impasse
and is unable to resolve it with the usual technique, it uses "weaker"
strategies to circumvent the dead end. In case one of these attempts
leads to success, the respective route is saved as a new rule, a chunk,
preventing the impasse to occur again. SOAR was created by John Laird,
Allen Newell and Paul Rosenbloom.

#### Neural Networks

There are two types of neural networks: biological and artificial.

A biological NN consists of neurons which are physically or functionally
connected with each other. Since each neuron can connect to multiple
other neurons the number of possible connections is exponentially high.
The connections between neurons are called synapses. Signalling along
these synapses happens via electrical signalling or chemical signalling,
which induces electrical signals. The chemical signalling works by
various neurotransmitters.

Artificial NN are divided by their goals. One is that of artificial
intelligence and the other cognitive modelling. Cognitive modelling NN
try to simulate biological NN in order to gain better understanding of
them, for example the brain. Until now the complexity of the brain and
similar structures has prevented a complete model from being devised, so
the cognitive modelling focuses on smaller parts like specific brain
regions. NNs in artificial intelligence are used to solve distinct
problems. But though their goals differ the methods applied are very
similar. An artificial NN consist of artificial neurons (nodes) which
are connected by mathematical functions. These functions can be of other
functions which in turn can be of yet other functions and so on. The
actual work is done by following the connections according to their
weights. Weights are properties of the connections defining the
probability of the specific route to be taken by the program and can be
changed by it, thus optimizing the main function. Hereby it is possible
to solve problems for which it is impossible to write a function "by
hand".

## Future Research

#### Brain imaging/activity measuring

As described in section 2.1. and 2.2. there are disadvantages of the
brain imaging methods. fMRI has a low temporal resolution, but EEG a low
spatial resolution. An interdisciplinary attempt is to combine both
methods, to reach both a high spatial and temporal resolution. This
technique (simultaneous EEG-measuring in the fMR) is used for instance
in studying children with extratemporal epilepsy. It is important to
assign the temporal progress to a region in which the epileptic seizure
has its roots. In December 2006 a conference in Munich discussed another
idea of this mixture of methods: the study of Alzheimer\'s disease. It
could be possible to recognise this disease very early. This could lead
to new therapies to reduce the speed and the amount of cell-dead. In
December of 2006 a conference in Munich discussed this eventuality.
Brain imaging methods are not only useful in medical approaches. Other
disciplines could benefit from the brain imaging methods and derive new
conclusions. For instance for social psychologist the brain imaging
methods are interesting. Experiments with psychopathic personalities are
only one possibility to explore the behaviour of humans. For literature
scientists there could be a possibility to study stylistic devices and
their effect of humans while reading a poem. Another attempt in future
research is to synchronise the direction of sight and the stimuli, that
was trigger for the change of direction. This complex project needs data
from eye-tracking experiments and data from fMRI-studies.

#### Unifying theories more unifying.

Since the mind is a single system it should be possible to explain it as
such without having to take different perspectives for every approach
(neurological,psychological,computational). Having such a theory would
enable us to understand our brain far more thorough than now, and might
eventually lead an everyday application. But until now there is no
working Unifying Theory of Cognition, which fulfils the requirements
stated by Allen Newell in his book Unified Theories of Cognition.
Accordingly a UTC has to explain: How intelligent organisms respond
flexibly to the environment. How they exhibit goal-directed behaviour
and choose goals rationally (and in response to interrupts: see previous
point). How they use symbols. How they learn from experience. Even
Newells own implementation SOAR does not reach these goals.

### Promising experiments

Here I collected the abstracts of a few recent findings, feel free to
modify or add to them.

\>\>Unintentional language switch \[\] Kho, K.H., Duffau, H., Gatignol,
P., Leijten, F.S.S., Ramsey, N.F., van Rijen, P.C. & Rutten, G-J.M.
(2007) Utrecht Abstract
1

We present two bilingual patients without language disorders in whom
involuntary language switching was induced. The first patient switched
from Dutch to English during a left-sided amobarbital Wada-test.
Functional magnetic resonance imaging yielded a predominantly left-sided
language distribution similar for both languages. The second patient
switched from French to Chinese during intraoperative electrocortical
stimulation of the left inferior frontal gyrus. We conclude that the
observed language switching in both cases was not likely the result of a
selective inhibition of one language, but the result of a temporary
disruption of brain areas that are involved in language switching. These
data complement the few lesion studies on (involuntary or unintentional)
language switching, and add to the functional neuroimaging studies of
switching, monitoring, and controlling the language in use.

\>\>Bilateral eye movement -\> memory Parker, A. & Dagnall, N. (2007)
Manchester Metropolitan University, One hundred and two participants
listened to 150 words, organised into ten themes (e.g. types of
vehicle), read by a male voice. Next, 34 of these participants moved
their eyes left and right in time with a horizontal target for thirty
seconds (saccadic eye movements); 34 participants moved their eyes up
and down in time with a vertical target; the remaining participants
stared straight ahead, focussed on a stationary target. After the eye
movements, all the participants listened to a mixture of words: 40
they\'d heard before, 40 completely unrelated new words, and 10 words
that were new but which matched one of the original themes. In each case
the participants had to say which words they\'d heard before, and which
were new. The participants who\'d performed sideways eye movements
performed better in all respects than the others: they correctly
recognised more of the old words as old, and more of the new words as
new. Crucially, they were fooled less often by the new words whose
meaning matched one of the original themes - that is they correctly
recognised more of them as new. This is important because mistakenly
identifying one of these \'lures\' as an old word is taken as a
laboratory measure of false memory. The performance of the participants
who moved their eyes vertically, or who stared ahead, did not differ
from each other. Episodic memory improvement induced by bilateral eye
movements is hypothesized to reflect enhanced interhemispheric
interaction, which is associated with superior episodic memory (S. D.
Christman & R. E. Propper. 2001). Implications for neuropsychological
mechanisms underlying eye movement desensitization and reprocessing (F.
Shapiro, 1989, 2001), a therapeutic technique for posttraumatic stress
disorder, are discussed

\>\>is the job satisfaction--job performance relationship spurious? A
meta-analytic examination

Nathan A. Bowling(Department of Psychology, Wright State University)
Abstract
2

The job satisfaction--job performance relationship has attracted much
attention throughout the history of industrial and organizational
psychology. Many researchers and most lay people believe that a causal
relationship exists between satisfaction and performance. In the current
study, however, analyses using meta-analytic data suggested that the
satisfaction--performance relationship is largely spurious. More
specifically, the satisfaction--performance relationship was partially
eliminated after controlling for either general personality traits
(e.g., Five Factor Model traits and core self-evaluations) or for work
locus of control and was almost completely eliminated after controlling
for organization-based self-esteem. The practical and theoretical
implications of these findings are discussed.

\>\>Mirror-touch synesthesia is linked with empathy

Michael J Banissy & Jamie Ward (Department of Psychology, University
College London)

Abstract 3
Watching another person being touched activates a similar neural circuit
to actual touch and, for some people with \'mirror-touch\' synesthesia,
can produce a felt tactile sensation on their own body. In this study,
we provide evidence for the existence of this type of synesthesia and
show that it correlates with heightened empathic ability. This is
consistent with the notion that we empathize with others through a
process of simulation.

### Discussion points

Where are the limitations of research? Can we rely on our intuitive idea
of our mind? What impact could a complete understanding of the brain
have on everyday life?

#### Brain activity as a false friend

In several experiments the outcome is not unambiguous. This hinders a
direct derivation from the data. In experiments with psychopathic
personalities researchers had to weaken their thesis, that persons with
missing activity in the frontal lobe are predetermined for being violent
psychopathic people, that are unethical murderers. Missing activity in
the frontal lobe leads to a disregulation of threshold for emotional,
impulsive or violent actions. But this also advantages for example fire
fighters or policemen, who have to withstand strong pressures and who
need a higher threshold. So missing activity is not a sufficient
criterion for psychopathic personalities.

## Conclusion

Today\'s work in the field of Cognitive Psychology gives several hints
how future work in this area may look like. In practical applications
improvements will probably mainly be driven by the limitations one faces
today. Here in particular the newer subfields of Cognitive Psychology
will develop quickly. How such changes look like heavily depends on the
character of future developments in technology. Especially improvements
in Cognitive Neuropsychology and Cognitive Neuroscience depend on the
advancements of the imaging techniques. In addition to that the
theoretical framework of the field will be influenced by such
developments. The parallel processing theory may still be modified
according to new insights in computer science. Thereby or eventually by
the acceptance of one of the already existing overarching theories the
theoretical basis for the current research could be reunified. But if it
takes another 30 years to fulfil Newell\'s dream of such a theory or if
it will happen rather quick is still open. As a rather young science
Cognitive Psychology still is subject to elementary changes. All its
practical and theoretical domains are steadily modified. Whether the
trends mentioned in this chapter are just dead ends or will cause a
revolution of the field could only be predicted which definitely is
hard.

## References

4
5
6
7
8
9
10
11

Anderson, John R., Lebiere, Christian, The Atomic Components of Thought,
Lawrence Erlbaum Associates, 1998\
Banich, Marie T., Neuropsycology - The Neural Bases of Mental Function,
Hougthon Mifflin Company, 1997\
E. Br. Goldstein, Cognitive Psychology, Wadsworth, 2004\
Lyon, G.Reid, Rumsey, Judith M.: Neuroimaging. A Window to Neurological
Foundations of Learning and Behaviour in Children. Baltimore. 1996.\
M. W. Eysenck, M. T. Keane, Cognitive Psychology - A Student\'s
Handbook, Psychology Press Ltd, 2000\
Thagard, Paul, Cognitive Science in Edward N. Zalta (ed.), The Stanford
Encyclopedia of Philosophy, 2004\

## Links

12
13


# Cognitive Psychology and Cognitive Neuroscience/Hints for good writing

First and most important: Always remember, that we are writing a
scientific book, not a novel; an essay; or a wikipedia article. For a
start you could read this
article

Try to write a consistent block of text, using subheadings, paragraphs
and footnotes. **Do not** make listings, keywords and in general
_articles_, but chapters.

Your first assignment is the introduction to your chapter. Keep in mind
that this is the basis for the rest of your chapter. You shouldn\'t
later rewrite your Introduction completely, because you did not know
what to write. This assignment already counts for your mark.

\'\'The mentioned APA Publishing Manual is not online. However, there is
a good overview
here

If you need help, check out the link section or write
Iroewer and
Aschoeke on their **discussion site**
or via email.


# Cognitive Psychology and Cognitive Neuroscience/Some useful syntax

## Referencing

From the Wikipedia about
footnotes.

On the Edit page, this is placed at the first insertion point of
citation:

:

    :   \<ref name=\"Perry\"\>Perry\'s Handbook, Sixth Edition,
        McGraw-Hill Co., 1984.\</ref\>

This is placed at the second insertion point of citation:

:

    :   \<ref name=\"Perry\"/\>

This is placed at the third insertion point of citation:

:

    :   \<ref name=\"Perry\"/\> \... and so forth for further insertion
        points

On the Edit page, this is placed in the References or the Footnotes
section, so the area, were the footnotes should appear:

:

    :   \<references/\>


# Cognitive Psychology and Cognitive Neuroscience/Cross References

The group Cross References responsibility is to make sure, that the
chapter are related to each other and that the mentioning of source is
not redundant. It will also help to connect groups which have similar
topics and may work together on certain issues.

The group works together with OverallStructure, to ensure that the book
in its final state is consistent, but the CRG will concentrate more on
sources and team work.

Our tools will be mostly non visible in the book, as our work will
happen on discussion pages, email and other not wiki related methods of
communication. However, we see our work as most important, as we have to
ensure the scientific mentioning of the sources and have an overview
over every page written in this project.


# Cognitive Psychology and Cognitive Neuroscience/OverallStructure

## OverallStructure

Our workgroup OverallStructure tries to work out this project of
Cognitive Psychology and Cognitive Neuroscience by **helping** people
how to do things right and remind them on the **laws** that we are all
restricted to when we publish. We try to give, the groups that work on
this book, useful help, inspiration and to remind them on certain
**dead-lines**. Especially at the end we are going to put the chapters
together as **one piece**, to make this a book worth being published and
being read.

Working voltage is necessary for a **workflow** of our project to
succeed. A workflow needs to be split up in sub-units. These
**subunits** fill up the work schedule which is necessary to keep track
of the workload and to stay in the timeframe. Here it is important to
delegate work to different groups and to have us that has an overlook
about what needs to be done and when it is due.

OverallStructure works with the group **CrossReferences** closely
together. This is required, because otherwise there is the possibility,
that we work counterproductive or that we work parallelly on the same
thing. Therefor our groups need to find out together what our priorities
are and how to put this into practice.

**Social skills** is a highly recommended to work in this group.
Remembering and criticizing people is risky field. Our comments need to
be productive and not to be offensive. We need close interaction with
everybody working on this project, just by that it is possible for us to
do the required work. We depend on the different groups and they depend
on us. Therefor we need some empathy for the nature of humans.

Hence we expect of people working on this project and especially of
ourselves:

-   We estimate people to have critical faculties, are able of some kind
    of self-reflection, self-discipline and tolerance.
-   In terms of working in groups, we anticipate everyone to be
    team-oriented, to cooperate with us and insight of the group, to be
    discountable, open to use communication skills and we hope to have
    at least one person in each group with some kind of
    leader-qualities.

OverallStructure emphasizes very much **group-work**. Working in groups
has a lot of advantages: It makes a project being more productive and
more flexible. Groups always optimize themselves, because each member of
the group enhances the work of the others resulting in improved
work-results. Each member harvest their own individuality and their own
creativity. A group contains a special selfcheck, each member not
cooperating get in some ways punished by the rest of the group.

Paraphrasing this we hope to find people being committed to this
project. Our group is a very challenging and implies responsibility from
both sides for this project to work and to succeed.


# Write Yourself a Scheme in 48 Hours/First Steps

First, you\'ll need to install GHC. On GNU/Linux, it\'s often
pre-installed or available via the package manager (`apt` or `yum` or
`pacman` for example, depending on your distribution). It\'s also
downloadable from <http://www.haskell.org/ghc/>. A binary package is
probably easiest, unless you really know what you\'re doing. It should
download and install like any other software package. This tutorial was
developed on GNU/Linux, but everything should also work on Windows, as
long as you know how to use the command line, or on the Macintosh from
within the Terminal.

For UNIX (or Windows
Emacs) users,
there is a pretty good Emacs
mode,
including syntax highlighting and automatic indentation. Windows users
can use Notepad or any other text editor: Haskell syntax is fairly
Notepad-friendly, though you have to be careful with the indentation.
Eclipse users might want to try the
eclipsefp plug-in.

Now, it\'s time for your first Haskell program. This program will read a
name off the command line and then print a greeting. Create a file
ending in \".hs\" and type the following text. Be sure to get the
indentation right, or else it may not compile.

``` haskell
 module Main where
 import System.Environment

 main :: IO ()
 main = do
     args <- getArgs
     putStrLn ("Hello, " ++ args !! 0)
```

Let\'s go through this code. The first two lines specify that we\'ll be
creating a module named Main that imports the
System module. Every
Haskell program begins with an action called `main` in a module named
`Main`. That module may import others, but it must be present for the
compiler to generate an executable file. Haskell is case-sensitive:
module names are always capitalized, definitions always uncapitalized.

The line `main :: IO ()` is a type declaration: it says that `main` is
of type `IO ()`, which is an IO action carrying along values of unit
type `()`. A unit type allows only one value, also denoted `()`, thus
holding no information. Type declarations in Haskell are optional: the
compiler figures them out automatically, and only complains if they
differ from what you\'ve specified. In this tutorial, I specify the
types of all declarations explicitly, for clarity. If you\'re following
along at home, you may want to omit them, because it\'s less to change
as we build our program.

The IO type is an instance of the Monad class (a class of types). Monad
is a concept. To say a value is of a type of the monad class is to say:

1.  there is (a certain type of) extra information attached to this
    value;
2.  most functions do not need to worry about these pieces of
    information.

In this example,

1.  the \"extra information\" is IO actions to be performed using the
    carried along values;
2.  while the basic value (which attached with information) is void,
    represented as `()`.

Both `IO [String]` and `IO ()` belong to the same `IO` monad type, but
they have different base types. They act on (and pass along) values of
different types, `[String]` and `()`.

\"value attached with (hidden) information\" is called \"Monadic
value\".

\"Monadic value\" is often called \"actions\", because the easiest way
to think about the using of IO monad is to think about a sequence of
actions affecting the outside world. The sequence of actions maybe pass
along basic values, and each action is able to act on the values.

Haskell is a functional language: instead of giving the computer a
sequence of instructions to carry out, you give it a collection of
definitions that tell it how to perform every function it might need.
These definitions use various compositions of actions and functions. The
compiler figures out an execution path that puts everything together.

To write one of these definitions, you set it up as an equation. The
left hand side defines a name, and optionally one or more *patterns*
(explained later) that will bind
variables. The right hand side defines some composition of other
definitions that tells the computer what to do when it encounters the
name. These equations behave just like ordinary equations in algebra:
you can always substitute the right hand side for the left within the
text of the program, and it\'ll evaluate to the same value. Called
\"referential transparency\", this property makes it significantly
easier to reason about Haskell programs than other languages.

How will we define our `main` action? We know that it must be an `IO ()`
action, which we want to read the command line args and print some
output, producing `()`, or nothing of value, eventually.

There are two ways to create an IO action (either directly or by calling
a function that performs them):

1.  Lift an ordinary value into the IO monad, using the
    `return`
    function.
2.  Combine two existing IO actions.

Since we want to do two things, we\'ll take the second approach. The
built-in action
getArgs
reads the command-line arguments and passes them along as a list of
strings. The built-in function
putStrLn
takes a string and creates an action that writes this string to the
console.

To combine these actions, we use a do-block. A do-block consists of a
series of lines, all lined up with the first non-whitespace character
after the do. Each line can have one of two forms:

1.  `name <- action1`
2.  `action2`

The first form binds the result of *action1* to *name*, to be available
in next actions. For example, if the type of *action1* is `IO [String]`
(an IO action returning a list of strings, as with `getArgs`), then
*name* will be bound in all the subsequent *actions* to the list of
strings thus passed along, through the use of \"bind\" operator
`>>=`.
The second form just executes *action2*, sequencing it with the next
line (should there be one) through the
`>>`
operator. The bind operator has different semantics for each monad: in
the case of the IO monad, it executes the actions sequentially,
performing whatever external side-effects that result from *actions*.
Because the semantics of this composition depend upon the particular
monad used, you cannot mix actions of different monad types in the same
do-block - only `IO` monad can be used (it\'s all in the same \"pipe\").

Of course, these *actions* may themselves call functions or complicated
expressions, passing along their results (either by calling the
`return`
function, or some other function that eventually does so). In this
example, we first take the first element of the argument list (at index
0, `args !! 0`), concatenate it onto the end of the string \"Hello, \"
(`"Hello, " ++`), and finally pass that to `putStrLn` which creates new
IO action, participating in the do-block sequencing.

A new action thus created, which is a combined sequence of actions as
described above, is stored in the identifier `main` of type `IO ()`. The
Haskell system notices this definition, and executes the action in it.

Strings are lists of characters in Haskell, so you can use any of the
list functions and operators on them. A full table of the standard
operators and their precedences follows:

  Operator(s)                        Precedence                           Associativity                                                  Description
  ---------------------------------- ------------------------------------ -------------------------------------------------------------- --------------------------------------------------------------------------------------------------
  `.`                                9                                    right                                                          function composition
  `<code>`{=html}                    `</code>`{=html}                     left                                                           list indexing
  `^`, `^^`, `**`                    8                                    right                                                          exponentiation (integer, fractional, and floating-point)
  `*`, `/`                           7                                    left                                                           multiplication, division
  `+`, `-`                           6                                    left                                                           addition, subtraction
  `:`                                5                                    right                                                          *cons* (list construction)
  `++`                               right                                list concatenation
  `` `elem` ``, `` `notElem` ``      4                                    left                                                           list membership
  `==`, `/=`, `<`, `<=`, `>=`, `>`   left                                 equality, inequality, and other relation operators
  `&&`                               3                                    right                                                          logical and
  `<code>`{=html}`<nowiki>`{=html}   `</nowiki>`{=html}`</code>`{=html}   2                                                              right
  `>>`, `>>=`                        1                                    left                                                           monadic bind ignoring the return value, monadic bind piping value to the next function
  `=<<`                              right                                reverse monadic bind (same as above, but arguments reversed)
  `$`                                0                                    right                                                          infix function application (`f $ x` is the same as `f x`, but right-associative instead of left)

To compile and run the program, try something like this:

`debian:/home/jdtang/haskell_tutorial/code# ghc -o hello_you --make listing2.hs`\
`debian:/home/jdtang/haskell_tutorial/code# ./hello_you Jonathan`\
`Hello, Jonathan`

The `-o` option specifies the name of the executable you want to create,
and then you just specify the name of the Haskell source file.


# Write Yourself a Scheme in 48 Hours/Parsing

## Making project scaffolding and getting `parsec`

We\'ll be using the Parsec
library. To install it, you\'ll need `cabal-install`, which is invoked
with the `cabal` command.

On Debian/Ubuntu: `sudo apt-get install cabal-install`. Alternatively,
you can use ghcup, which works for
many platforms.

After installing `cabal-install`, let\'s make a project:

``` sh
$ cabal update
$ mkdir myProject
$ cd myProject
$ cabal init
```

Now edit `myProject.cabal` such that `parsec` is listed in
`build-depends` listing, in addition to `base`.

Now, the project can be run using `cabal run`:

    Building executable 'myProject' for myProject-0.1.0.0..
    [1 of 1] Compiling Main             ( app/Main.hs )
    Linking myProject-0.1.0.0/x/myProject/build/myProject/myProject ...
    Hello, Haskell!

The last line is the output by the program.

## Writing a Simple Parser

Now, let\'s try writing a very simple parser.

Start by adding these lines to the import section of `app/Main.hs`
(which was generated by `cabal init`):

``` haskell
import Text.ParserCombinators.Parsec hiding (spaces)
import System.Environment
```

This makes the Parsec library functions available to us, except the
`spaces` function, whose name conflicts with a function that we\'ll be
defining later.

Now, we\'ll define a parser that recognizes one of the symbols allowed
in Scheme identifiers:

``` haskell
symbol :: Parser Char
symbol = oneOf "!#$%&|*+-/:<=>?@^_~"
```

This is another example of a monad: in this case, the \"extra
information\" that is being hidden is all the info about position in the
input stream, backtracking record, first and follow sets, etc. Parsec
takes care of all of that for us. We need only use the Parsec library
function
`oneOf`,
and it\'ll recognize a single one of any of the characters in the string
passed to it. Parsec provides a number of pre-built parsers: for
example,
`letter`
and
`digit`
are library functions. And as you\'re about to see, you can compose
primitive parsers into more sophisticated productions.

Let\'s define a function to call our parser and handle any possible
errors:

``` haskell
readExpr :: String -> String
readExpr input = case parse symbol "lisp" input of
    Left err -> "No match: " ++ show err
    Right val -> "Found value"
```

As you can see from the type signature, `readExpr` is a function (`->`)
from a `String` to a `String`. We name the parameter `input`, and pass
it, along with the `symbol` parser we defined above to the Parsec
function
`parse`.
The second parameter to `parse` is a name for the input. It is used for
error messages.

`parse` can return either the parsed value or an error, so we need to
handle the error case. Following typical Haskell convention, Parsec
returns an
`Either`
data type, using the `Left` constructor to indicate an error and the
`Right` one for a normal value.

We use a `case...of` construction to match the result of `parse` against
these alternatives. If we get a `Left` value (error), then we bind the
error itself to `err` and return \"No match\" with the string
representation of the error. If we get a `Right` value, we bind it to
`val`, ignore it, and return the string \"Found value\".

The `case...of` construction is an example of pattern matching, which we
will see in much greater detail later
on.

Finally, we need to change our main function to call `readExpr` and
print out the result:

``` haskell
main :: IO ()
main = do
         (expr:_) <- getArgs
         putStrLn (readExpr expr)
```

To compile and run this, you can specify the command line parameters
after the \"executable target\" which the project scaffolding generated
with the call to `init` in the first section. For example:

`$ cabal run myProject $`\
`Found value`\
`$ cabal run myProject a`\
`No match: "lisp" (line 1, column 1):`\
`unexpected "a"`

## Whitespace

Next, we\'ll add a series of improvements to our parser that\'ll let it
recognize progressively more complicated expressions. The current parser
chokes if there\'s whitespace preceding our symbol:

`$ cabal run myProject "   %"`\
`No match: "lisp" (line 1, column 1):`\
`unexpected " "`

Let\'s fix that, so that we ignore whitespace.

First, lets define a parser that recognizes any number of whitespace
characters. Incidentally, this is why we included the `hiding (spaces)`
clause when we imported Parsec: there\'s already a
`spaces`
function in that library, but it doesn\'t quite do what we want it to.
(For that matter, there\'s also a parser called
`lexeme`
that does exactly what we want, but we\'ll ignore that for pedagogical
purposes.)

``` haskell
spaces :: Parser ()
spaces = skipMany1 space
```

Just as functions can be passed to functions, so can actions. Here we
pass the Parser action
`space`
to the Parser action
`skipMany1`,
to get a Parser that will recognize one or more spaces.

Now, let\'s edit our parse function so that it uses this new parser:

``` haskell
readExpr input = case parse (spaces >> symbol) "lisp" input of
    Left err -> "No match: " ++ show err
    Right val -> "Found value"
```

We touched briefly on the `>>` (\"bind\") operator in lesson 2, where we
mentioned that it was used behind the scenes to combine the lines of a
do-block. Here, we use it explicitly to combine our whitespace and
symbol parsers. However, bind has completely different semantics in the
Parser and IO monads. In the Parser monad, bind means \"Attempt to match
the first parser, then attempt to match the second with the remaining
input, and fail if either fails.\" In general, bind will have wildly
different effects in different monads; it\'s intended as a general way
to structure computations, and so needs to be general enough to
accommodate all the different types of computations. Read the
documentation for the monad to figure out precisely what it does.

Compile and run this code. Note that since we defined `spaces` in terms
of `skipMany1`, it will no longer recognize a plain old single
character. Instead you *have to* precede a symbol with some whitespace.
We\'ll see how this is useful shortly:

`$ cabal run myProject "   %"`\
`Found value`\
`$ cabal run myProject %`\
`No match: "lisp" (line 1, column 1):`\
`unexpected "%"`\
`expecting space`\
`$ cabal run myProject "   abc"`\
`No match: "lisp" (line 1, column 4):`\
`unexpected "a"`\
`expecting space`

## Return Values

Right now, the parser doesn\'t *do* much of anything---it just tells us
whether a given string can be recognized or not. Generally, we want
something more out of our parsers: we want them to convert the input
into a data structure that we can traverse easily. In this section, we
learn how to define a data type, and how to modify our parser so that it
returns this data type.

First, we need to define a data type that can hold any Lisp value:

``` haskell
data LispVal = Atom String
             | List [LispVal]
             | DottedList [LispVal] LispVal
             | Number Integer
             | String String
             | Bool Bool
```

This is an example of an *algebraic data type*: it defines a set of
possible values that a variable of type LispVal can hold. Each
alternative (called a *constructor* and separated by `|`) contains a tag
for the constructor along with the type of data that the constructor can
hold. In this example, a `LispVal` can be:

1.  An `Atom`, which stores a String naming the atom
2.  A `List`, which stores a list of other LispVals (Haskell lists are
    denoted by brackets); also called a *proper* list
3.  A `DottedList`, representing the Scheme form `(a b . c)`; also
    called an *improper* list. This stores a list of all elements but
    the last, and then stores the last element as another field
4.  A `Number`, containing a Haskell Integer
5.  A `String`, containing a Haskell String
6.  A `Bool`, containing a Haskell boolean value

Constructors and types have different namespaces, so you can have both a
constructor named `String` and a type named `String`. Both types and
constructor tags always begin with capital letters.

Next, let\'s add a few more parsing functions to create values of these
types. A string is a double quote mark, followed by any number of
non-quote characters, followed by a closing quote mark:

``` haskell
parseString :: Parser LispVal
parseString = do
                char '"'
                x <- many (noneOf "\"")
                char '"'
                return $ String x
```

We\'re back to using the `do`-notation instead of the `>>` operator.
This is because we\'ll be retrieving the value of our parse (returned by
`many(noneOf "\"")`) and manipulating it, interleaving some other parse
operations in the meantime. In general, use `>>` if the actions don\'t
return a value, `>>=` if you\'ll be immediately passing that value into
the next action, and `do`-notation otherwise.

Once we\'ve finished the parse and have the Haskell String returned from
`many`, we apply the `String` constructor (from our LispVal data type)
to turn it into a `LispVal`. Every constructor in an algebraic data type
also acts like a function that turns its arguments into a value of its
type. It also serves as a pattern that can be used in the left-hand side
of a pattern-matching expression; we saw an example of this in Lesson
3.1 when we matched our parser
result against the two constructors in the `Either` data type.

We then apply the built-in function
`return`
to lift our `LispVal` into the `Parser` monad. Remember, each line of a
`do`-block must have the same type, but the result of our String
constructor is just a plain old LispVal. `return` lets us wrap that up
in a Parser action that consumes no input but returns it as the inner
value. Thus, the whole `parseString` action will have type
`Parser LispVal`.

The `$` operator is infix function application: it\'s the same as if
we\'d written `return (String x)`, but `$` is right associative and low
precedence, letting us eliminate some parentheses. Since `$` is an
operator, you can do anything with it that you\'d normally do to a
function: pass it around, partially apply it, etc. In this respect, it
functions like the Lisp function
`apply`.

Now let\'s move on to Scheme variables. An
*atom*
is a letter or symbol, followed by any number of letters, digits, or
symbols:

``` haskell
parseAtom :: Parser LispVal
parseAtom = do
              first <- letter <|> symbol
              rest <- many (letter <|> digit <|> symbol)
              let atom = first:rest
              return $ case atom of
                         "#t" -> Bool True
                         "#f" -> Bool False
                         _    -> Atom atom
```

Here, we introduce another Parsec combinator, the choice operator
`<|>`.
This tries the first parser, then if it fails, tries the second. If
either succeeds, then it returns the value returned by that parser. The
first parser must fail before it consumes any input: we\'ll see later
how to implement backtracking.

Once we\'ve read the first character and the rest of the atom, we need
to put them together. The \"`let`\" statement defines a new variable
`atom`. We use the list cons operator `:` for this. Instead of `:`, we
could have used the concatenation operator `++` like this
`[first] ++ rest`; recall that `first` is just a single character, so we
convert it into a singleton list by putting brackets around it.

Then we use a case expression to determine which `LispVal` to create and
return, matching against the literal strings for true and false. The
underscore `_` alternative is a readability trick: case blocks continue
until a `_` case (or fail any case which also causes the failure of the
whole `case` expression), think of `_` as a *wildcard*. So if the code
falls through to the `_` case, it always matches, and returns the value
of `atom`.

Finally, we create one more parser, for numbers. This shows one more way
of dealing with monadic values:

``` haskell
parseNumber :: Parser LispVal
parseNumber = liftM (Number . read) $ many1 digit
```

It\'s easiest to read this backwards, since both function application
(`$`) and function composition (`.`) associate to the right. The parsec
combinator
many1
matches one or more of its argument, so here we\'re matching one or more
digits. We\'d like to construct a number `LispVal` from the resulting
string, but we have a few type mismatches. First, we use the built-in
function
read
to convert that string into a number. Then we pass the result to
`Number` to get a `LispVal`. The function composition operator `.`
creates a function that applies its right argument and then passes the
result to the left argument, so we use that to combine the two function
applications.

Unfortunately, the result of `many1 digit` is actually a
`Parser String`, so our combined `Number . read` still can\'t operate on
it. We need a way to tell it to just operate on the value inside the
monad, giving us back a `Parser LispVal`. The standard function `liftM`
does exactly that, so we apply `liftM` to our `Number . read` function,
and then apply the result of that to our parser.

We also have to import the Monad module up at the top of our program to
get access to `liftM`:

``` haskell
import Control.Monad
```

This style of programming---relying heavily on function composition,
function application, and passing functions to functions---is very
common in Haskell code. It often lets you express very complicated
algorithms in a single line, breaking down intermediate steps into other
functions that can be combined in various ways. Unfortunately, it means
that you often have to read Haskell code from right-to-left and keep
careful track of the types. We\'ll be seeing many more examples
throughout the rest of the tutorial, so hopefully you\'ll get pretty
comfortable with it.

Let\'s create a parser that accepts either a string, a number, or an
atom:

``` haskell
parseExpr :: Parser LispVal
parseExpr = parseAtom
         <|> parseString
         <|> parseNumber
```

And edit readExpr so it calls our new parser:

``` haskell
readExpr :: String -> String
readExpr input = case parse parseExpr "lisp" input of
    Left err -> "No match: " ++ show err
    Right _ -> "Found value"
```

Compile and run this code, and you\'ll notice that it accepts any
number, string, or symbol, but not other strings:

`$ cabal run myProject "\"this is a string\""`\
`Found value`\
`$ cabal run myProject 25`\
`Found value`\
`$ cabal run myProject symbol`\
`Found value`\
`$ cabal run myProject (symbol)`\
`` bash: syntax error near unexpected token `symbol' ``\
`$ cabal run myProject "(symbol)"`\
`No match: "lisp" (line 1, column 1):`\
`unexpected "("`\
`expecting letter, "\"" or digit`

## Recursive Parsers: Adding lists, dotted lists, and quoted datums

Next, we add a few more parser actions to our interpreter. Start with
the parenthesized lists that make Lisp famous:

``` haskell
parseList :: Parser LispVal
parseList = liftM List $ sepBy parseExpr spaces
```

This works analogously to `parseNumber`, first parsing a series of
expressions separated by whitespace (`sepBy parseExpr spaces`) and then
apply the List constructor to it within the Parser monad. Note too that
we can pass `parseExpr` to
sepBy,
even though it\'s an action we wrote ourselves.

The dotted-list parser is somewhat more complex, but still uses only
concepts that we\'re already familiar with:

``` haskell
parseDottedList :: Parser LispVal
parseDottedList = do
    head <- endBy parseExpr spaces
    tail <- char '.' >> spaces >> parseExpr
    return $ DottedList head tail
```

Note how we can sequence together a series of Parser actions with `>>`
and then use the whole sequence on the right hand side of a
do-statement. The expression `char '.' >> spaces` returns a `Parser ()`,
then combining that with `parseExpr` gives a `Parser LispVal`, exactly
the type we need for the do-block.

Next, let\'s add support for the single-quote syntactic sugar of Scheme:

``` haskell
parseQuoted :: Parser LispVal
parseQuoted = do
    char '\''
    x <- parseExpr
    return $ List [Atom "quote", x]
```

Most of this is fairly familiar stuff: it reads a single quote
character, reads an expression and binds it to `x`, and then returns
`(quote x)`, to use Scheme notation. The `Atom` constructor works like
an ordinary function: you pass it the String you\'re encapsulating, and
it gives you back a LispVal. You can do anything with this LispVal that
you normally could, like put it in a list.

Finally, edit our definition of parseExpr to include our new parsers:

``` haskell
parseExpr :: Parser LispVal
parseExpr = parseAtom
         <|> parseString
         <|> parseNumber
         <|> parseQuoted
         <|> do char '('
                x <- try parseList <|> parseDottedList
                char ')'
                return x
```

This illustrates one last feature of Parsec: backtracking. `parseList`
and `parseDottedList` recognize identical strings up to the dot; this
breaks the requirement that a choice alternative may not consume any
input before failing. The
try
combinator attempts to run the specified parser, but if it fails, it
backs up to the previous state. This lets you use it in a choice
alternative without interfering with the other alternative.

Compile and run this code:

`$ cabal run myProject "(a test)"`\
`Found value`\
`$ cabal run myProject "(a (nested) test)"`\
`Found value`\
`$ cabal run myProject "(a (dotted . list) test)"`\
`Found value`\
`$ cabal run myProject "(a '(quoted (dotted . list)) test)"`\
`Found value`\
`$ cabal run myProject "(a '(imbalanced parens)"`\
`No match: "lisp" (line 1, column 24):`\
`unexpected end of input`\
`expecting space or ")"`

Note that by referring to `parseExpr` within our parsers, we can nest
them arbitrarily deep. Thus, we get a full Lisp reader with only a few
definitions. That\'s the power of recursion.


# Write Yourself a Scheme in 48 Hours/Evaluation, Part 1

## Beginning the Evaluator

Currently, we\'ve just been printing out whether or not we recognize the
given program fragment. We\'re about to take the first steps towards a
working Scheme interpreter: assigning values to program fragments.
We\'ll be starting with baby steps, but fairly soon you\'ll be
progressing to working with computations.

Let\'s start by telling Haskell how to print out a string representation
of the various possible `LispVal`s:

``` haskell

showVal :: LispVal -> String
showVal (String contents) = "\"" ++ contents ++ "\""
showVal (Atom name) = name
showVal (Number contents) = show contents
showVal (Bool True) = "#t"
showVal (Bool False) = "#f"
```

This is our first real introduction to pattern matching. Pattern
matching is a way of destructuring an algebraic data type, selecting a
code clause based on its constructor and then binding the components to
variables. Any constructor can appear in a pattern; that pattern matches
a value if the tag is the same as the value\'s tag and all subpatterns
match their corresponding components. Patterns can be nested arbitrarily
deep, with matching proceeding in an inside → outside, left → right
order. The clauses of a function definition are tried in textual order,
until one of the patterns matches. If this is confusing, you\'ll see
some examples of deeply-nested patterns when we get further into the
evaluator.

For now, you only need to know that each clause of the above definition
matches one of the constructors of `LispVal`, and the right-hand side
tells what to do for a value of that constructor.

The `List` and `DottedList` clauses work similarly, but we need to
define a helper function `unwordsList` to convert the contained list
into a string:

``` haskell
showVal (List contents) = "(" ++ unwordsList contents ++ ")"
showVal (DottedList head tail) = "(" ++ unwordsList head ++ " . " ++ showVal tail ++ ")"
```

The `unwordsList` function works like the Haskell Prelude\'s
`unwords`
function, which glues together a list of words with spaces. Since we\'re
dealing with a list of `LispVal`s instead of words, we define a function
that first converts the `LispVal`s into their string representations and
then applies `unwords` to it:

``` haskell
unwordsList :: [LispVal] -> String
unwordsList = unwords . map showVal
```

Our definition of unwordsList doesn\'t include any arguments. This is an
example of *point-free style*: writing definitions purely in terms of
function composition and partial application, without regard to
individual values or \"points\". Instead, we define it as the
composition of a couple of built-in functions. First, we partially-apply
`map`
to `showVal`, which creates a function that takes a list of `LispVal`s
and returns a list of their string representations. Haskell functions
are *curried*: this means that a function of two arguments, like `map`,
is really a function that returns a function of one argument. As a
result, if you supply only a single argument, you get back a function of
one argument that you can pass around, compose, and apply later. In this
case, we compose it with unwords: `map showVal` converts a list of
`LispVal`s to a list of their string representations, and then `unwords`
joins the result together with spaces.

We used the function
`show`
above. This standard Haskell function lets you convert any type that\'s
an instance of the class `Show` into a string. We\'d like to be able to
do the same with `LispVal`, so we make it into a member of the class
`Show`, defining its `show` method as `showVal`:

``` haskell
instance Show LispVal where show = showVal
```

A full treatment of type classes is beyond the scope of this tutorial;
you can find more information in other
tutorials and the
Haskell 2010
report.

Let\'s try things out by changing our readExpr function so it returns
the string representation of the value actually parsed, instead of just
\"Found value\":

``` haskell
readExpr input = case parse parseExpr "lisp" input of
    Left err -> "No match: " ++ show err
    Right val -> "Found " ++ show val
```

And compile and run...

`$ ghc -package parsec -o parser listing4.1.hs`\
`$ ./parser "(1 2 2)"`\
`Found (1 2 2)`\
`$ ./parser "'(1 3 (\"this\" \"one\"))"`\
`Found (quote (1 3 ("this" "one")))`

## Beginnings of an evaluator: Primitives

Now, we start with the beginnings of an evaluator. The purpose of an
evaluator is to map some \"code\" data type into some \"data\" data
type, the result of the evaluation. In Lisp, the data *types* for both
code and data are the same, so our evaluator will return a `LispVal`.
Other languages often have more complicated code structures, with a
variety of syntactic forms.

Evaluating numbers, strings, booleans, and quoted lists is fairly
simple: return the datum itself.

``` haskell

eval :: LispVal -> LispVal
eval val@(String _) = val
eval val@(Number _) = val
eval val@(Bool _) = val
eval (List [Atom "quote", val]) = val
```

This introduces a new type of pattern. The notation `val@(String _)`
matches against any `LispVal` that\'s a string and then binds `val` to
the *whole* `LispVal`, and not just the contents of the `String`
constructor. The result has type `LispVal` instead of type `String`. The
underbar is the \"don\'t care\" variable, matching any value yet not
binding it to a variable. It can be used in any pattern, but is
especially useful with @-patterns (where you bind the variable to the
whole pattern) and with simple constructor-tests where you\'re just
interested in the tag of the constructor.

The last clause is our first introduction to nested patterns. The type
of data contained by `List` is `[LispVal]`, a list of `LispVal`s. We
match *that* against the specific two-element list
`[Atom "quote", val]`, a list where the first element is the symbol
\"quote\" and the second element can be anything. Then we return that
second element.

Let\'s integrate `eval` into our existing code. Start by changing
`readExpr` back so it returns the expression instead of a string
representation of the expression:

``` haskell
readExpr :: String -> LispVal
readExpr input = case parse parseExpr "lisp" input of
    Left err -> String $ "No match: " ++ show err
    Right val -> val
```

And then change our main function to read an expression, evaluate it,
convert it to a string, and print it out. Now that we know about the
`>>=` monad sequencing operator and the function composition operator,
let\'s use them to make this a bit more concise:

``` haskell
main :: IO ()
main = getArgs >>= print . eval . readExpr . head
```

Here, we take the result of the `getArgs` action (a list of strings) and
pass it into the composition of:

1.  take the first value (`head`);
2.  parse it (`readExpr`);
3.  evaluate it (`eval`);
4.  convert it to a string and print it (`print`).

Compile and run the code the normal way:

`$ ghc -package parsec -o eval listing4.2.hs`\
`$ ./eval "'atom" `\
`atom`\
`$ ./eval 2`\
`2`\
`$ ./eval "\"a string\""`\
`"a string"`\
`$ ./eval "(+ 2 2)"`\
\
`Fail: listing6.hs:83: Non-exhaustive patterns in function eval`

We still can\'t do all that much useful with the program (witness the
failed `(+ 2 2)` call), but the basic skeleton is in place. Soon, we\'ll
be extending it with some functions to make it useful.

## Adding basic primitives

Next, we\'ll improve our Scheme so we can use it as a simple calculator.
It\'s still not yet a \"programming language\", but it\'s getting close.

Begin by adding a clause to eval to handle function application.
Remember that all clauses of a function definition must be placed
together and are evaluated in textual order, so this should go after the
other eval clauses:

``` haskell
eval (List (Atom func : args)) = apply func $ map eval args
```

This is another nested pattern, but this time we match against the cons
operator \":\" instead of a literal list. Lists in Haskell are really
syntactic sugar for a chain of cons applications and the empty list:
`[1, 2, 3, 4] = 1:(2:(3:(4:[])))`. By pattern-matching against cons
itself instead of a literal list, we\'re saying \"give me the rest of
the list\" instead of \"give me the second element of the list\". For
example, if we passed `(+ 2 2)` to eval, `func` would be bound to \"+\"
and `args` would be bound to `[Number 2, Number 2]`.

The rest of the clause consists of a couple of functions we\'ve seen
before and one we haven\'t defined yet. We have to recursively evaluate
each argument, so we map `eval` over the args. This is what lets us
write compound expressions like `(+ 2 (- 3 1) (* 5 4))`. Then we take
the resulting list of evaluated arguments, and pass it and the original
function to apply:

``` haskell
apply :: String -> [LispVal] -> LispVal
apply func args = maybe (Bool False) ($ args) $ lookup func primitives
```

The built-in function
`lookup`
looks up a key (its first argument) in a list of pairs. However, lookup
will fail if no pair in the list contains the matching key. To express
this, it returns an instance of the built-in type
`Maybe`.
We use the function
`maybe`
to specify what to do in case of either success or failure. If the
function isn\'t found, we return a `Bool False` value, equivalent to
`#f` (we\'ll add more robust error-checking later). If it *is* found, we
apply it to the arguments using `($ args)`, an operator section of the
function application operator.

Next, we define the list of primitives that we support:

``` haskell
primitives :: [(String, [LispVal] -> LispVal)]
primitives = [("+", numericBinop (+)),
              ("-", numericBinop (-)),
              ("*", numericBinop (*)),
              ("/", numericBinop div),
              ("mod", numericBinop mod),
              ("quotient", numericBinop quot),
              ("remainder", numericBinop rem)]
```

Look at the type of `primitives`. It is a list of pairs, just like
`lookup` expects, *but the values of the pairs are functions from
`[LispVal]` to `LispVal`*. In Haskell, you can easily store functions in
other data structures, though the functions must all have the same type.

Also, the functions that we store are themselves the result of a
function, `numericBinop`, which we haven\'t defined yet. This takes a
primitive Haskell function (often an operator section) and wraps it with
code to unpack an argument list, apply the function to it, and wrap the
result up in our `Number` constructor.

``` haskell
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> LispVal
numericBinop op params = Number $ foldl1 op $ map unpackNum params

unpackNum :: LispVal -> Integer
unpackNum (Number n) = n
unpackNum (String n) = let parsed = reads n :: [(Integer, String)] in
                           if null parsed
                              then 0
                              else fst $ parsed !! 0
unpackNum (List [n]) = unpackNum n
unpackNum _ = 0
```

As with R5RS Scheme, we don\'t limit ourselves to only two arguments.
Our numeric operations can work on a list of any length, so
`(+ 2 3 4) = 2 + 3 + 4`, and `(- 15 5 3 2) = 15 - 5 - 3 - 2`. We use the
built-in function
`foldl1`
to do this. It essentially changes every cons operator in the list to
the binary function we supply, `op`.

Unlike R5RS Scheme, we\'re implementing a form of *weak typing*. That
means that if a value can be interpreted as a number (like the string
\"2\"), we\'ll use it as one, even if it\'s tagged as a string. We do
this by adding a couple extra clauses to `unpackNum`. If we\'re
unpacking a string, attempt to parse it with Haskell\'s built-in
`reads`
function, which returns a list of pairs of (parsed value, remaining
string).

For lists, we pattern-match against the one-element list and try to
unpack that. Anything else falls through to the next case.

If we can\'t parse the number, for any reason, we\'ll return 0 for now.
We\'ll fix this shortly so that it signals an error.

Compile and run this the normal way. Note how we get nested expressions
\"for free\" because we call eval on each of the arguments of a
function:

`$ ghc -package parsec -o eval listing7.hs`\
`$ ./eval "(+ 2 2)"`\
`4`\
`$ ./eval "(+ 2 (-4 1))"`\
`2`\
`$ ./eval "(+ 2 (- 4 1))"`\
`5`\
`$ ./eval "(- (+ 4 6 3) 3 5 2)"`\
`3`


# Write Yourself a Scheme in 48 Hours/Error Checking and Exceptions

Currently, there are a variety of places within the code where we either
ignore errors or silently assign \"default\" values like `#f` or 0 that
make no sense. Some languages -- like Perl and PHP -- get along fine
with this approach. However, it often means that errors pass silently
throughout the program until they become big problems, which means
rather inconvenient debugging sessions for the programmer. We\'d like to
signal errors as soon as they happen and immediately break out of
execution.

First, we need to import `Control.Monad.Except` to get access to
Haskell\'s built-in error functions:

``` haskell
import Control.Monad.Except
```

On Debian based systems this needs `libghc6-mtl-dev` installed.

Then, we should define a data type to represent an error:

``` haskell
data LispError = NumArgs Integer [LispVal]
               | TypeMismatch String LispVal
               | Parser ParseError
               | BadSpecialForm String LispVal
               | NotFunction String String
               | UnboundVar String String
               | Default String
```

This is a few more constructors than we need at the moment, but we might
as well foresee all the other things that can go wrong in the
interpreter later. Next, we define how to print out the various types of
errors and make `LispError` an instance of `Show`:

``` haskell
showError :: LispError -> String
showError (UnboundVar message varname)  = message ++ ": " ++ varname
showError (BadSpecialForm message form) = message ++ ": " ++ show form
showError (NotFunction message func)    = message ++ ": " ++ show func
showError (NumArgs expected found)      = "Expected " ++ show expected
                                       ++ " args; found values " ++ unwordsList found
showError (TypeMismatch expected found) = "Invalid type: expected " ++ expected
                                       ++ ", found " ++ show found
showError (Parser parseErr)             = "Parse error at " ++ show parseErr

instance Show LispError where show = showError
```

Then we define a type to represent functions that may throw a
`LispError` or return a value. Remember how
`parse`
used an
`Either`
data type to represent exceptions? We take the same approach here:

``` haskell
type ThrowsError = Either LispError
```

Type constructors are curried just like functions, and can also be
partially applied. A full type would be `Either LispError Integer` or
`Either LispError LispVal`, but we want to say `ThrowsError LispVal` and
so on. We only partially apply `Either` to `LispError`, creating a type
constructor `ThrowsError` that we can use on any data type.

`Either` is yet another instance of a monad. In this case, the \"extra
information\" being passed between `Either` actions is whether or not an
error occurred. Bind applies its function if the `Either` action holds a
normal value, or passes an error straight through without computation.
This is how exceptions work in other languages, but because Haskell is
lazily-evaluated, there\'s no need for a separate control-flow
construct. If bind determines that a value is already an error, the
function is never called.

The `Control.Monad.Except` library automatically gives the `Either`
monad two other functions besides the standard monadic ones:

1.  `throwError`,
    which takes an `Error` value and lifts it into the `Left` (error)
    constructor of an `Either`
2.  `catchError`,
    which takes an `Either` action and a function that turns an error
    into another `Either` action. If the action represents an error, it
    applies the function, which you can use to, e.g. turn the error
    value into a normal one via `return` or re-throw as a different
    error.

In our program, we\'ll be converting all of our errors to their string
representations and returning that as a normal value. Let\'s create a
helper function to do that for us:

``` haskell
trapError action = catchError action (return . show)
```

The result of calling `trapError` is another `Either` action which will
always have valid (`Right`) data. We still need to extract that data
from the `Either` monad so it can be passed around to other functions:

``` haskell
extractValue :: ThrowsError a -> a
extractValue (Right val) = val
```

We purposely leave `extractValue` undefined for a `Left` constructor,
because that represents a programmer error. We intend to use
`extractValue` only after a `catchError`, so it\'s better to fail fast
than to inject bad values into the rest of the program.

Now that we have all the basic infrastructure, it\'s time to start using
our error-handling functions. Remember how our parser had previously
just returned a string saying \"No match\" on an error? Let\'s change it
so that it wraps and throws the original `ParseError`:

``` haskell
readExpr :: String -> ThrowsError LispVal
readExpr input = case parse parseExpr "lisp" input of
     Left err -> throwError $ Parser err
     Right val -> return val
```

Here, we first wrap the original `ParseError` with the `LispError`
constructor `Parser`, and then use the built-in function
`throwError`
to return that in our `ThrowsError` monad. Since `readExpr` now returns
a monadic value, we also need to wrap the other case in a return
function.

Next, we change the type signature of `eval` to return a monadic value,
adjust the return values accordingly, and add a clause to throw an error
if we encounter a pattern that we don\'t recognize:

``` haskell
eval :: LispVal -> ThrowsError LispVal
eval val@(String _) = return val
eval val@(Number _) = return val
eval val@(Bool _) = return val
eval (List [Atom "quote", val]) = return val
eval (List (Atom func : args)) = mapM eval args >>= apply func
eval badForm = throwError $ BadSpecialForm "Unrecognized special form" badForm
```

Since the function application clause calls `eval` (which now returns a
monadic value) recursively, we need to change that clause. First, we had
to change `map` to
`mapM`,
which maps a monadic function over a list of values, sequences the
resulting actions together with bind, and then returns a list of the
inner results. Inside the `Error` monad, this sequencing performs all
computations sequentially but throws an error value if any one of them
fails -- giving you `Right [results]` on success, or `Left error` on
failure. Then, we used the monadic \"bind\" operation to pass the result
into the partially applied \"apply func\", again returning an error if
either operation failed.

Next, we change `apply` itself so that it throws an error if it doesn\'t
recognize the function:

``` haskell
apply :: String -> [LispVal] -> ThrowsError LispVal
apply func args = maybe (throwError $ NotFunction "Unrecognized primitive function args" func)
                        ($ args)
                        (lookup func primitives)
```

We *didn\'t* add a return statement to the function application
`($ args)`. We\'re about to change the type of our primitives, so that
the function returned from the lookup itself returns a `ThrowsError`
action:

``` haskell
primitives :: [(String, [LispVal] -> ThrowsError LispVal)]
```

And, of course, we need to change the numericBinop function that
implements these primitives so it throws an error if there\'s only one
argument:

``` haskell
numericBinop :: (Integer -> Integer -> Integer) -> [LispVal] -> ThrowsError LispVal
numericBinop op           []  = throwError $ NumArgs 2 []
numericBinop op singleVal@[_] = throwError $ NumArgs 2 singleVal
numericBinop op params        = mapM unpackNum params >>= return . Number . foldl1 op
```

We use an at-pattern to capture the single-value case because we want to
include the actual value passed in for error-reporting purposes. Here,
we\'re looking for a list of exactly one element, and we don\'t care
what that element is. We also need to use `mapM` to sequence the results
of `unpackNum`, because each individual call to `unpackNum` may fail
with a `TypeMismatch`:

``` haskell
unpackNum :: LispVal -> ThrowsError Integer
unpackNum (Number n) = return n
unpackNum (String n) = let parsed = reads n in
                           if null parsed
                             then throwError $ TypeMismatch "number" $ String n
                             else return $ fst $ parsed !! 0
unpackNum (List [n]) = unpackNum n
unpackNum notNum     = throwError $ TypeMismatch "number" notNum
```

Finally, we need to change our main function to use this whole big error
monad. This can get a little complicated, because now we\'re dealing
with *two* monads (`Either` (for errors) and `IO`). As a result, we go
back to do-notation, because it\'s nearly impossible to use point-free
style when the result of one monad is nested inside another:

``` haskell
main :: IO ()
main = do
     args <- getArgs
     evaled <- return $ liftM show $ readExpr (args !! 0) >>= eval
     putStrLn $ extractValue $ trapError evaled
```

Here\'s what this new function is doing:

1.  `args` is the list of command-line arguments.
2.  `evaled` is the result of:
    1.  taking first argument (`args !! 0`);
    2.  parsing it (`readExpr`);
    3.  passing it to `eval` (`>>= eval`; the bind operation has higher
        precedence than `$`);
    4.  calling `show` on it within the `Error` monad. (Note also that
        the whole action has type `IO (Either LispError String)`, giving
        `evaled` type `Either LispError String`. It has to be, because
        our `trapError` function can only convert errors to `String`s,
        and that type must match the type of normal values.)
3.  Caught is the result of:
    1.  calling `trapError` on `evaled`, converting errors to their
        string representation;
    2.  calling `extractValue` to get a `String` out of this
        `Either LispError String` action;
    3.  printing the results through `putStrLn`.

Compile and run the new code, and try throwing it a couple errors:

`$ ghc -package parsec -o errorcheck [../code/listing5.hs listing5.hs]`\
`$ ./errorcheck "(+ 2 \"two\")"`\
`Invalid type: expected number, found "two"`\
`$ ./errorcheck "(+ 2)"`\
`Expected 2 args; found values 2`\
`$ ./errorcheck "(what? 2)"`\
`Unrecognized primitive function args: "what?"`

Some readers have reported that you need to add a `--make` flag to build
this example, and presumably all further listings. This tells GHC to
build a complete executable, searching out all dependencies listed in
the import statements. The command above works on my system, but if it
fails on yours, give `--make` a try.