Export translations
Jump to navigation
Jump to search
Settings
Group
FP Homework 1
FP Laboratory 1
FP Laboratory 10
FP Laboratory 11
FP Laboratory 12
FP Laboratory 2
FP Laboratory 3
FP Laboratory 4
FP Laboratory 5
FP Laboratory 6
FP Laboratory 7
FP Laboratory 9
Functional programming
Main Page
Language
aa - Afar
ab - Abkhazian
abs - Ambonese Malay
ace - Achinese
ady - Adyghe
ady-cyrl - Adyghe (Cyrillic script)
aeb - Tunisian Arabic
aeb-arab - Tunisian Arabic (Arabic script)
aeb-latn - Tunisian Arabic (Latin script)
af - Afrikaans
ak - Akan
aln - Gheg Albanian
am - Amharic
an - Aragonese
ang - Old English
anp - Angika
ar - Arabic
arc - Aramaic
arn - Mapuche
arq - Algerian Arabic
ary - Moroccan Arabic
arz - Egyptian Arabic
as - Assamese
ase - American Sign Language
ast - Asturian
atj - Atikamekw
av - Avaric
avk - Kotava
awa - Awadhi
ay - Aymara
az - Azerbaijani
azb - South Azerbaijani
ba - Bashkir
ban - Balinese
bar - Bavarian
bbc - Batak Toba
bbc-latn - Batak Toba (Latin script)
bcc - Southern Balochi
bcl - Central Bikol
be - Belarusian
be-tarask - Belarusian (Taraškievica orthography)
bg - Bulgarian
bgn - Western Balochi
bh - Bhojpuri
bho - Bhojpuri
bi - Bislama
bjn - Banjar
bm - Bambara
bn - Bangla
bo - Tibetan
bpy - Bishnupriya
bqi - Bakhtiari
br - Breton
brh - Brahui
bs - Bosnian
btm - Batak Mandailing
bto - Iriga Bicolano
bug - Buginese
bxr - Russia Buriat
ca - Catalan
cbk-zam - Chavacano
cdo - Min Dong Chinese
ce - Chechen
ceb - Cebuano
ch - Chamorro
cho - Choctaw
chr - Cherokee
chy - Cheyenne
ckb - Central Kurdish
co - Corsican
cps - Capiznon
cr - Cree
crh - Crimean Turkish
crh-cyrl - Crimean Tatar (Cyrillic script)
crh-latn - Crimean Tatar (Latin script)
cs - Czech
csb - Kashubian
cu - Church Slavic
cv - Chuvash
cy - Welsh
da - Danish
de - German
de-at - Austrian German
de-ch - Swiss High German
de-formal - German (formal address)
din - Dinka
diq - Zazaki
dsb - Lower Sorbian
dtp - Central Dusun
dty - Doteli
dv - Divehi
dz - Dzongkha
ee - Ewe
egl - Emilian
el - Greek
eml - Emiliano-Romagnolo
en - English
en-ca - Canadian English
en-gb - British English
eo - Esperanto
es - Spanish
es-419 - Latin American Spanish
es-formal - español (formal)
et - Estonian
eu - Basque
ext - Extremaduran
fa - Persian
ff - Fulah
fi - Finnish
fit - Tornedalen Finnish
fj - Fijian
fo - Faroese
fr - French
frc - Cajun French
frp - Arpitan
frr - Northern Frisian
fur - Friulian
fy - Western Frisian
ga - Irish
gag - Gagauz
gan - Gan Chinese
gan-hans - Gan (Simplified)
gan-hant - Gan (Traditional)
gcr - Guianan Creole
gd - Scottish Gaelic
gl - Galician
glk - Gilaki
gn - Guarani
gom - Goan Konkani
gom-deva - Goan Konkani (Devanagari script)
gom-latn - Goan Konkani (Latin script)
gor - Gorontalo
got - Gothic
grc - Ancient Greek
gsw - Swiss German
gu - Gujarati
gv - Manx
ha - Hausa
hak - Hakka Chinese
haw - Hawaiian
he - Hebrew
hi - Hindi
hif - Fiji Hindi
hif-latn - Fiji Hindi (Latin script)
hil - Hiligaynon
ho - Hiri Motu
hr - Croatian
hrx - Hunsrik
hsb - Upper Sorbian
ht - Haitian Creole
hu - Hungarian
hu-formal - magyar (formal)
hy - Armenian
hyw - Western Armenian
hz - Herero
ia - Interlingua
id - Indonesian
ie - Interlingue
ig - Igbo
ii - Sichuan Yi
ik - Inupiaq
ike-cans - Eastern Canadian (Aboriginal syllabics)
ike-latn - Eastern Canadian (Latin script)
ilo - Iloko
inh - Ingush
io - Ido
is - Icelandic
it - Italian
iu - Inuktitut
ja - Japanese
jam - Jamaican Creole English
jbo - Lojban
jut - Jutish
jv - Javanese
ka - Georgian
kaa - Kara-Kalpak
kab - Kabyle
kbd - Kabardian
kbd-cyrl - Kabardian (Cyrillic script)
kbp - Kabiye
kg - Kongo
khw - Khowar
ki - Kikuyu
kiu - Kirmanjki
kj - Kuanyama
kjp - Eastern Pwo
kk - Kazakh
kk-arab - Kazakh (Arabic script)
kk-cn - Kazakh (China)
kk-cyrl - Kazakh (Cyrillic script)
kk-kz - Kazakh (Kazakhstan)
kk-latn - Kazakh (Latin script)
kk-tr - Kazakh (Turkey)
kl - Kalaallisut
km - Khmer
kn - Kannada
ko - Korean
ko-kp - Korean (North Korea)
koi - Komi-Permyak
kr - Kanuri
krc - Karachay-Balkar
kri - Krio
krj - Kinaray-a
krl - Karelian
ks - Kashmiri
ks-arab - Kashmiri (Arabic script)
ks-deva - Kashmiri (Devanagari script)
ksh - Colognian
ku - Kurdish
ku-arab - Kurdish (Arabic script)
ku-latn - Kurdish (Latin script)
kum - Kumyk
kv - Komi
kw - Cornish
ky - Kyrgyz
la - Latin
lad - Ladino
lb - Luxembourgish
lbe - Lak
lez - Lezghian
lfn - Lingua Franca Nova
lg - Ganda
li - Limburgish
lij - Ligurian
liv - Livonian
lki - Laki
lmo - Lombard
ln - Lingala
lo - Lao
loz - Lozi
lrc - Northern Luri
lt - Lithuanian
ltg - Latgalian
lus - Mizo
luz - Southern Luri
lv - Latvian
lzh - Literary Chinese
lzz - Laz
mai - Maithili
map-bms - Basa Banyumasan
mdf - Moksha
mg - Malagasy
mh - Marshallese
mhr - Eastern Mari
mi - Maori
min - Minangkabau
mk - Macedonian
ml - Malayalam
mn - Mongolian
mni - Manipuri
mnw - Mon
mo - Moldovan
mr - Marathi
mrj - Western Mari
ms - Malay
mt - Maltese
mus - Creek
mwl - Mirandese
my - Burmese
myv - Erzya
mzn - Mazanderani
na - Nauru
nah - Nāhuatl
nan - Min Nan Chinese
nap - Neapolitan
nb - Norwegian Bokmål
nds - Low German
nds-nl - Low Saxon
ne - Nepali
new - Newari
ng - Ndonga
niu - Niuean
nl - Dutch
nl-informal - Nederlands (informeel)
nn - Norwegian Nynorsk
no - Norwegian
nov - Novial
nrm - Norman
nso - Northern Sotho
nv - Navajo
ny - Nyanja
nys - Nyungar
oc - Occitan
olo - Livvi-Karelian
om - Oromo
or - Odia
os - Ossetic
pa - Punjabi
pag - Pangasinan
pam - Pampanga
pap - Papiamento
pcd - Picard
pdc - Pennsylvania German
pdt - Plautdietsch
pfl - Palatine German
pi - Pali
pih - Norfuk / Pitkern
pl - Polish
pms - Piedmontese
pnb - Western Punjabi
pnt - Pontic
prg - Prussian
ps - Pashto
pt - Portuguese
pt-br - Brazilian Portuguese
qqq - Message documentation
qu - Quechua
qug - Chimborazo Highland Quichua
rgn - Romagnol
rif - Riffian
rm - Romansh
rmy - Vlax Romani
rn - Rundi
ro - Romanian
roa-tara - Tarantino
ru - Russian
rue - Rusyn
rup - Aromanian
ruq - Megleno-Romanian
ruq-cyrl - Megleno-Romanian (Cyrillic script)
ruq-latn - Megleno-Romanian (Latin script)
rw - Kinyarwanda
sa - Sanskrit
sah - Sakha
sat - Santali
sc - Sardinian
scn - Sicilian
sco - Scots
sd - Sindhi
sdc - Sassarese Sardinian
sdh - Southern Kurdish
se - Northern Sami
sei - Seri
ses - Koyraboro Senni
sg - Sango
sgs - Samogitian
sh - Serbo-Croatian
shi - Tachelhit
shi-latn - Tachelhit (Latin script)
shi-tfng - Tachelhit (Tifinagh script)
shn - Shan
shy-latn - Shawiya (Latin script)
si - Sinhala
simple - Simple English
sk - Slovak
skr - Saraiki
skr-arab - Saraiki (Arabic script)
sl - Slovenian
sli - Lower Silesian
sm - Samoan
sma - Southern Sami
sn - Shona
so - Somali
sq - Albanian
sr - Serbian
sr-ec - Serbian (Cyrillic script)
sr-el - Serbian (Latin script)
srn - Sranan Tongo
ss - Swati
st - Southern Sotho
stq - Saterland Frisian
sty - cебертатар
su - Sundanese
sv - Swedish
sw - Swahili
szl - Silesian
ta - Tamil
tay - Tayal
tcy - Tulu
te - Telugu
tet - Tetum
tg - Tajik
tg-cyrl - Tajik (Cyrillic script)
tg-latn - Tajik (Latin script)
th - Thai
ti - Tigrinya
tk - Turkmen
tl - Tagalog
tly - Talysh
tn - Tswana
to - Tongan
tpi - Tok Pisin
tr - Turkish
tru - Turoyo
ts - Tsonga
tt - Tatar
tt-cyrl - Tatar (Cyrillic script)
tt-latn - Tatar (Latin script)
tum - Tumbuka
tw - Twi
ty - Tahitian
tyv - Tuvinian
tzm - Central Atlas Tamazight
udm - Udmurt
ug - Uyghur
ug-arab - Uyghur (Arabic script)
ug-latn - Uyghur (Latin script)
uk - Ukrainian
ur - Urdu
uz - Uzbek
uz-cyrl - Uzbek (Cyrillic script)
uz-latn - Uzbek (Latin script)
ve - Venda
vec - Venetian
vep - Veps
vi - Vietnamese
vls - West Flemish
vmf - Main-Franconian
vo - Volapük
vot - Votic
vro - Võro
wa - Walloon
war - Waray
wo - Wolof
wuu - Wu Chinese
xal - Kalmyk
xh - Xhosa
xmf - Mingrelian
xsy - Saisiyat
yi - Yiddish
yo - Yoruba
yue - Cantonese
za - Zhuang
zea - Zeelandic
zgh - Standard Moroccan Tamazight
zh - Chinese
zh-cn - Chinese (China)
zh-hans - Simplified Chinese
zh-hant - Traditional Chinese
zh-hk - Chinese (Hong Kong)
zh-mo - Chinese (Macau)
zh-my - Chinese (Malaysia)
zh-sg - Chinese (Singapore)
zh-tw - Chinese (Taiwan)
zu - Zulu
Format
Export for off-line translation
Export in native format
Fetch
{{DISPLAYTITLE:FP Homework 1}}== Basic notes == In all exercises you are required to write something to standard output. You can use the same strategy as in [[FP_Laboratory_7 | Laboratory 7]]. Lets define a type for the result: <syntaxhighlight lang="Haskell">type Result = [String]</syntaxhighlight> Now, if you want to print this result nicely on the screen, you can use: <syntaxhighlight lang="Haskell"> pp :: Result -> IO () pp x = putStr (concat (map (++"\n") x)) </syntaxhighlight> == Example - Ships == Implement the function <code>ships</code> which has 2 arguments. First argument is a list of strings representing play field of one player row by row from top to bottom ('o' - square containing a ship, ' ' - empty square). Second list contains coordinates of squares attacked by second player. Print actual state of a play in the way where every row and column will be labelled by its number or letter, 'o' will be square with ship not attacked yet, 'x' square with ship already attacked, '.' already attacked empty square, ' ' empty square not attacked yet. You can consider that the size of play-field is 10x10. <div style="float: right"> [[File:Video logo.png|80px|link=https://youtu.be/NC6pb3R7A0g]]</div> <div style="clear:both"></div> <syntaxhighlight lang="Haskell"> ships :: Result -> [(Char, Int)] -> Result sampleInput = [" o o ", " ooo ", " oo ", " ", " o ", " o ", " o ", " ", " ", " oooo "] </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > Prelude>pp(ships sampleInput [('a',1),('d',1),('d',2),('c',1),('b',1),('e',1),('f',1),('g',1),('c',7),('c',10)]) 10 x o 9 ooo 8 oo 7 . 6 o 5 o 4 o 3 2 . 1..xxxx. abcdefghij </syntaxhighlight> <div class="mw-collapsible mw-collapsed" data-collapsetext="Hide solution" data-expandtext="Show solution"> <syntaxhighlight lang="Haskell"> import Data.Char ( ord ) type Result = [String] pp :: Result -> IO () pp x = putStr (concat (map (++"\n") x)) sampleInput :: Result sampleInput = [" o o ", " ooo ", " oo ", " ", " o ", " o ", " o ", " ", " ", " oooo "] ships :: Result -> [(Char, Int)] -> Result ships input coordinates = let coordinates' = [(ord ch - ord 'a' +1 ,ri) |(ch, ri)<-coordinates] get x ch | elem x coordinates' = if ch == 'o' then 'x' else '.' | otherwise = ch niceShow x = let number' = show x in if length number' == 1 then " "++number' else " "++number' nicePrint result = reverse [niceShow number ++ row|(number,row)<-zip [1..] result] ++ [" abcdefghij"] in nicePrint ([[get (ci,ri) ch |(ci,ch)<- zip [1..] row ]| (ri,row)<-zip [1..] (reverse input)]) </syntaxhighlight> </div> <div style="clear:both"></div> == 1 - Magic 15 Puzzle == Implement the function <code>puzzle</code>, it will simulate the game similar to [https://en.wikipedia.org/wiki/15_puzzle 15 Puzzle]. In our case, we have 25 squares, where 24 squares are ocupied by tiles with big case letters from <code>'A'</code> to <code>'X'</code>. One tile is free, it is denotated by <code>' '</code>. In one move, you can move a tile (denotated by its letter) into the free one. The function gets the original configuration and a sequence of '''valid''' moves. It will output the resulting configuration. <syntaxhighlight lang="Haskell"> puzzle2 = ["AC DE", "FBHIJ", "KGLNO", "PQMRS", "UVWXT"] puzzle :: Result -> [Char] -> Result </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > *Main> pp(puzzle puzzle2 "CBGLMRST") ABCDE FGHIJ KLMNO PQRST UVWX </syntaxhighlight> == 2 - Crossword Answers == Implement the function <code>answers</code> that takes as an input a crosword puzzle's solution and outputs all words from this solution. Words will be divided into two lists, first for lines (from left to right) and second for columns (from top to bottom). A word is written only if it is longer than just one character. *TIP: ''Use the function'' <code>words :: String -> [String]</code> ''to split lines into sequence of words.'' <syntaxhighlight lang="Haskell" class="myDark" > *Main> words "ABC cdef ghijkl" ["ABC","cdef","ghijkl"] </syntaxhighlight> <syntaxhighlight lang="Haskell"> solution1 = ["DAD SEND", "O EAST A", "W A ITSY", "NERF N T ", " A ARK U ", " S T SYNC", "MESH A A", "A EVER R", "NEAR D D"] answers :: Result -> ([String],[String]) </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > *Main> answers solution1 (["DAD","SEND","EAST","ITSY","NERF","ARK","SYNC","MESH","EVER","NEAR"],["DOWN","MAN","EASE","DEAR","FATHER","STINKS","YARD","STUN","DAY","CARD"]) </syntaxhighlight> == 3 - Creating Crossword Puzzles== In this task, you will implement a function, that helps when creating the crossword puzzle. The function <code>positions</code> takes an input, an ''outline'' for the future puzzle, and prints all positions, where we need to put some words. The outline compose from empty spaces (<code>'.'</code>), where we can put some character, and from black boxes (<code>'#'</code>), where there are no characters. In our crossword puzzles, words need to be placed in all sequences of empty spaces, that are at least two spaces long. The functions output is all starting positions where we need to put some words. Positions are pairs <code>(row, column)</code>. They are indexed from topmost leftmost corner with coordinates <code>(0,0)</code>. Consider only words in '''lines''' (for rows, we can rotate and flip the puzzle outline and use the same function). <syntaxhighlight lang="Haskell"> --An example of a crossword puzzle with the same outline is in the previous task. crossword = ["...##....", ".#....##.", ".#.##....", "....#.#.#", "#.#...#.#", "#.#.#....", "....##.#.", ".##....#.", "....##.#."] positions :: Result -> [(Int,Int)] </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > *Main> positions crossword [(0,0),(0,5),(1,2),(2,5),(3,0),(4,3),(5,5),(6,0),(7,3),(8,0)] </syntaxhighlight> == 4 - Decoder == On possibility how to encode text is to replace frequent pairs of characters by a new (until that time, not used) character. In this task, you should implement a function that decodes such encoded text. The function <code>decode</code> takes an encoded text and a vocabulary. Vocabulary is a sequence of pairs, where the first element is an encoded character (<code>Char</code>) and the second element is the original pair (as <code>String</code> of the length 2). The result is an original text. In fact, it is the text from the parameter, where all encoded characters were replaced by its original pairs of characters. <syntaxhighlight lang="Haskell"> decode :: String -> [(Char,String)] -> String </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > *Main> decode "HAHA" [('E',"AB"),('F',"CD"),('G',"EF"),('H',"GG")] "ABCDABCDAABCDABCDA" </syntaxhighlight> == 5 - Prefix Decoder == One possibility, how to code characters into the binary code is to use prefix coding (an example can be [https://en.wikipedia.org/wiki/Huffman_coding Huffman coding] ). In this coding, a given code is not ''a prefix'' of any other code. If for example, one letter is coded as <code>101</code>, then no other letter's code starts with the same sequence <code>101</code>. In this task, write a function <code>toText</code>, that takes an encoded binary sequence (in our case <code>String</code> composed from <code>1</code> and <code>0</code>) along with a dictionary, and produces the original text like a result. Dictionary compose of pairs, where each pair contains the encrypted character (<code>Char</code>) and a sequence (<code>String</code>) of <code>1</code> and <code>0</code> - assigned prefix code. Safely assume, that all inputs are '''valid'''. <syntaxhighlight lang="Haskell"> dictionary = [('a',"0"),('b',"101"),('c',"100"),('d',"111"),('e',"1101"),('f',"1100")] toText :: String->[(Char, String)]->String </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > *Main> toText "01011001111101" dictionary "abcde" </syntaxhighlight> == 6 - Chess position == Implement the function <code>chess</code> which has 2 arguments of the type <code>[String]</code>. Each of these strings in both lists contain 3 characters: * first stands for chess piece ('K' - king, 'Q' - queen, 'R' - rook, 'B' - bishop, 'N' - knight, 'P' - pawn) * second stands for column ('a'-'h') * third is row ('1'-'8') First list contains actual positions of white pieces and second list positions of black pieces. Print actual state of a chessboard in the way where '.' stands for empty square, capital letters mean white pieces and small letters mean black pieces. Each row and column should be labeled by its number or letter. <syntaxhighlight lang="Haskell"> chess :: [String] -> [String] -> Result </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > Prelude> pp( chess["Ke1","Ra1","Rh1","Pa2","Be5"] ["Ke8","Ra8","Rh8","Pa7","Qd8","Bc8","Nb8"]) 8rnbqk..r 7p....... 6........ 5....B... 4........ 3........ 2P....... 1R...K..R abcdefgh </syntaxhighlight> == 7 - Ticktacktoe == Implement the function <code>ticktack</code> which has 2 arguments. First argument is a tuple of natural numbers and defines the number of columns and rows of a play field. Coordinates are counted from bottom left corner. Second list contains a record of a match of ticktacktoe game given by coordinates on which played in turns player 'x' and player 'o'. Print actual state of the game in the way where play-field will be bordered by characters '-' and '|', empty squares ' ' and characters 'x' and 'o' will be on squares where the players have played. <syntaxhighlight lang="Haskell"> ticktack::(Int,Int) -> [(Int,Int)] -> Result </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > Prelude>pp(ticktack (8,8) [(1,1),(8,8),(2,2),(3,3),(4,2),(3,2)]) ---------- | o| | | | | | | | | | o | | xox | |x | ---------- </syntaxhighlight> == 8 - Maze == Implement the function <code>maze</code> which has 2 arguments. First argument is a list of strings representing a maze row by row from top to bottom ('*' - wall, ' ' - empty square, 's' - starting position). At the beginning we are at position 's'. Second argument is list of directions ('d' - down, 'u' - up, 'l' - left, 'r' - right). Each letter means move by one square in the given direction and on this new square character '.' is placed. Print actual state of a maze. <syntaxhighlight lang="Haskell"> maze :: Result -> String -> Result sampleInput = ["*********", "*s* * *", "* * * * *", "* * * * *", "* * *", "******* *", " *", "*********"] </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > Prelude>pp(maze sampleInput "dddrruuurrdddrrddllllll") ********* *s*...* * *.*.*.* * *.*.*.* * *...*...* *******.* .......* ********* </syntaxhighlight> == 9 - Minesweeper == Implement the function <code>minesweeper</code> which has 1 argument of the type list of strings. The strings represent play field row by row from top to bottom ('*' - mine, ' ' - empty square). Print play field in a way where mines will be represented by '*' and on each square not containing a mine will be a number - count of all mines directly adjacent to this square (it can be adjacent vertically, horizontally or diagonally). <syntaxhighlight lang="Haskell"> minesweeper :: Result -> Result sampleInput = [" ", " * ", " * ", " * ", " *", "*** ", "* * ", "*** "] </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > Prelude>pp(minesweeper sampleInput) 1110000 1*11110 1122*10 001*221 233211* ***2011 *8*3000 ***2000 </syntaxhighlight> == 10 - Turtle == Implement a function that will draw the movement of a turtle in a rectangular grid. It will be named <code>draw</code> and it will have one parameter - a list movements. Our turtle can move only horizontally or vertically. Each movement will be described by a pair (its type will be <code>(Char, Int)</code>), where the first character denotates a direction of this movement and the second its length. Possible directions are: <b>l</b>eft, <b>r</b>ight, <b>u</b>p, and <b>d</b>own. As the result, function <code>draw</code> returns a smallest possible rectangle with all turtle's movements. Each block from the grid will be represented with one character. If it was visited by our turtle, then it will be <code>'X'</code>, if it was not, then it will be <code>' '</code>. <syntaxhighlight lang="Haskell"> draw :: [(Char, Int)] -> Result </syntaxhighlight> <syntaxhighlight lang="Haskell" class="myDark" > *Main> pp (draw [('u',5),('r',5),('d',5),('l',10),('d',5),('r',5),('u',5)]) XXXXXX X X X X X X X X XXXXXXXXXXX X X X X X X X X XXXXXX </syntaxhighlight>
Navigation menu
Personal tools
English
Log in
Namespaces
Special page
Variants
Views
More
Search
Main page
Education
Functional programming
Functional programming - presentations
Functional programming - laboratories
Programming Languages and Compilers
Practical Functional Programming
History Entries
Programming paradigms
C#
Tools
Special pages