https://wiki.haskell.org/api.php?action=feedcontributions&user=Chrycheng&feedformat=atomHaskellWiki - User contributions [en]2024-03-19T05:42:57ZUser contributionsMediaWiki 1.35.5https://wiki.haskell.org/index.php?title=99_questions/11_to_20&diff=1556699 questions/11 to 202007-09-14T09:21:22Z<p>Chrycheng: Provided an alternative solution to problem 17.</p>
<hr />
<div>__NOTOC__<br />
<br />
This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems] and [http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html Ninety-Nine Lisp Problems].<br />
<br />
== Problem 11 ==<br />
<br />
(*) Modified run-length encoding. <br />
Modify the result of problem 10 in such a way that if an element has no duplicates it is simply copied into the result list. Only elements with duplicates are transferred as (N E) lists.<br />
<br />
<pre><br />
Example:<br />
* (encode-modified '(a a a a b c c a a d e e e e))<br />
((4 A) B (2 C) (2 A) D (4 E))<br />
<br />
Example in Haskell:<br />
P11> encodeModified "aaaabccaadeeee"<br />
[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
data ListItem a = Single a | Multiple Int a<br />
deriving (Show)<br />
<br />
encodeModified :: Eq a => [a] -> [ListItem a]<br />
encodeModified = map encodeHelper . encode<br />
where<br />
encodeHelper (1,x) = Single x<br />
encodeHelper (n,x) = Multiple n x<br />
</haskell><br />
<br />
Again, like in problem 7, we need a utility type because lists in haskell are homogeneous. Afterwards we use the <hask>encode</hask> function from problem 10 and map single instances of a list item to <hask>Single</hask> and multiple ones to <hask>Multiple</hask>.<br />
<br />
The ListItem definition contains 'deriving (Show)' so that we can get interactive output.<br />
<br />
== Problem 12 ==<br />
<br />
(**) Decode a run-length encoded list. <br />
Given a run-length code list generated as specified in problem 11. Construct its uncompressed version.<br />
<br />
<pre><br />
Example in Haskell:<br />
P12> decodeModified [Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']<br />
"aaaabccaadeeee"<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
decodeModified :: [ListItem a] -> [a]<br />
decodeModified = concatMap decodeHelper<br />
where<br />
decodeHelper (Single x) = [x]<br />
decodeHelper (Multiple n x) = replicate n x<br />
</haskell><br />
<br />
We only need to map single instances of an element to a list containing only one element and multiple ones to a list containing the specified number of elements and concatenate these lists.<br />
<br />
== Problem 13 ==<br />
<br />
(**) Run-length encoding of a list (direct solution). <br />
Implement the so-called run-length encoding data compression method directly. I.e. don't explicitly create the sublists containing the duplicates, as in problem 9, but only count them. As in problem P11, simplify the result list by replacing the singleton lists (1 X) by X.<br />
<br />
<pre><br />
Example:<br />
* (encode-direct '(a a a a b c c a a d e e e e))<br />
((4 A) B (2 C) (2 A) D (4 E))<br />
<br />
Example in Haskell:<br />
P13> encodeDirect "aaaabccaadeeee"<br />
[Multiple 4 'a',Single 'b',Multiple 2 'c',Multiple 2 'a',Single 'd',Multiple 4 'e']<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
encode' :: Eq a => [a] -> [(Int,a)]<br />
encode' = foldr helper []<br />
where<br />
helper x [] = [(1,x)]<br />
helper x (y:ys)<br />
| x == snd y = (1+fst y,x):ys<br />
| otherwise = (1,x):y:ys<br />
<br />
encodeDirect :: Eq a => [a] -> [ListItem a]<br />
encodeDirect = map encodeHelper . encode'<br />
where<br />
encodeHelper (1,x) = Single x<br />
encodeHelper (n,x) = Multiple n x<br />
</haskell><br />
<br />
First of all we could rewrite the function <hask>encode</hask> from problem 10 in a way that is does not create the sublists. Thus, I decided to traverse the original list from right to left (using <hask>foldr</hask>) and to prepend each element to the resulting list in the proper way. Thereafter we only need to modify the function <hask>encodeModified</hask> from problem 11 to use <hask>encode'</hask>.<br />
<br />
== Problem 14 ==<br />
<br />
(*) Duplicate the elements of a list.<br />
<br />
<pre><br />
Example:<br />
* (dupli '(a b c c d))<br />
(A A B B C C C C D D)<br />
<br />
Example in Haskell:<br />
> dupli [1, 2, 3]<br />
[1,1,2,2,3,3]<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
dupli [] = []<br />
dupli (x:xs) = x:x:dupli xs<br />
</haskell><br />
<br />
or, using list comprehension syntax:<br />
<br />
<haskell><br />
dupli list = concat [[x,x] | x <- list]<br />
</haskell><br />
<br />
or, using the list monad:<br />
<haskell><br />
dupli xs = xs >>= (\x -> [x,x])<br />
</haskell><br />
<br />
== Problem 15 ==<br />
<br />
(**) Replicate the elements of a list a given number of times.<br />
<br />
<pre><br />
Example:<br />
* (repli '(a b c) 3)<br />
(A A A B B B C C C)<br />
<br />
Example in Haskell:<br />
> repli "abc" 3<br />
"aaabbbccc"<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
repli :: [a] -> Int -> [a]<br />
repli xs n = concatMap (replicate n) xs<br />
</haskell><br />
<br />
== Problem 16 ==<br />
(**) Drop every N'th element from a list.<br />
<br />
<pre><br />
Example:<br />
* (drop '(a b c d e f g h i k) 3)<br />
(A B D E G H K)<br />
<br />
Example in Haskell:<br />
*Main> dropEvery "abcdefghik" 3<br />
"abdeghk"<br />
</pre><br />
<br />
An iterative solution:<br />
<haskell><br />
dropEvery :: [a] -> Int -> [a]<br />
dropEvery [] _ = []<br />
dropEvery (x:xs) n = dropEvery' (x:xs) n 1 where<br />
dropEvery' (x:xs) n i = (if (n `divides` i) then<br />
[] else<br />
[x])<br />
++ (dropEvery' xs n (i+1))<br />
dropEvery' [] _ _ = []<br />
divides x y = y `mod` x == 0<br />
</haskell><br />
<br />
or using zip:<br />
<haskell><br />
dropEvery n = map snd . filter ((n/=) . fst) . zip (cycle [1..n])<br />
</haskell><br />
<br />
== Problem 17 ==<br />
<br />
(*) Split a list into two parts; the length of the first part is given.<br />
<br />
Do not use any predefined predicates.<br />
<br />
<pre><br />
Example:<br />
* (split '(a b c d e f g h i k) 3)<br />
( (A B C) (D E F G H I K))<br />
<br />
Example in Haskell:<br />
*Main> split "abcdefghik" 3<br />
("abc", "defghik")<br />
</pre><br />
<br />
Solution using take and drop:<br />
<haskell><br />
split xs n = (take n xs, drop n xs)<br />
</haskell><br />
<br />
Alternatively, we have the following recursive solution:<br />
<haskell><br />
split :: [a] -> Int -> ([a], [a])<br />
split [] _ = ([], [])<br />
split l@(x : xs) n | n > 0 = (x : fst splitSub, snd splitSub)<br />
| otherwise = ([], l)<br />
where splitSub = split xs (n - 1)<br />
</haskell><br />
<br />
Note that this function, with the parameters in the other order, exists as <hask>splitAt</hask>.<br />
<br />
<br />
== Problem 18 ==<br />
<br />
(**) Extract a slice from a list.<br />
<br />
Given two indices, i and k, the slice is the list containing the elements between the i'th and i'th element of the original list (both limits included). Start counting the elements with 1.<br />
<br />
<pre><br />
Example:<br />
* (slice '(a b c d e f g h i k) 3 7)<br />
(C D E F G)<br />
<br />
Example in Haskell:<br />
*Main> slice ['a','b','c','d','e','f','g','h','i','k'] 3 7<br />
"cdefg"<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
slice xs (i+1) k = take (k-i) $ drop i xs<br />
</haskell><br />
<br />
== Problem 19 ==<br />
<br />
(**) Rotate a list N places to the left.<br />
<br />
Hint: Use the predefined functions length and (++).<br />
<br />
<pre><br />
Examples:<br />
* (rotate '(a b c d e f g h) 3)<br />
(D E F G H A B C)<br />
<br />
* (rotate '(a b c d e f g h) -2)<br />
(G H A B C D E F)<br />
<br />
Examples in Haskell:<br />
*Main> rotate ['a','b','c','d','e','f','g','h'] 3<br />
"defghabc"<br />
<br />
*Main> rotate ['a','b','c','d','e','f','g','h'] (-2)<br />
"ghabcdef"<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
rotate [] _ = []<br />
rotate l 0 = l<br />
rotate (x:xs) (n+1) = rotate (xs ++ [x]) n<br />
rotate l n = rotate l (length l + n)<br />
</haskell><br />
<br />
There are two separate cases:<br />
* If n > 0, move the first element to the end of the list n times.<br />
* If n < 0, convert the problem to the equivalent problem for n > 0 by adding the list's length to n.<br />
<br />
or using cycle:<br />
<haskell><br />
rotate xs n = take len . drop (n `mod` len) . cycle $ xs<br />
where len = length xs<br />
</haskell><br />
<br />
or<br />
<br />
<haskell><br />
rotate xs n = if n >= 0 then<br />
drop n xs ++ take n xs<br />
else let l = ((length xs) + n) in<br />
drop l xs ++ take l xs<br />
</haskell><br />
<br />
== Problem 20 ==<br />
<br />
(*) Remove the K'th element from a list.<br />
<br />
Example in Prolog:<br />
<pre><br />
?- remove_at(X,[a,b,c,d],2,R).<br />
X = b<br />
R = [a,c,d]<br />
</pre><br />
<br />
Example in Lisp:<br />
<pre><br />
* (remove-at '(a b c d) 2)<br />
(A C D)<br />
</pre><br />
(Note that this only returns the residue list, while the Prolog version also returns the deleted element.)<br />
<br />
Example in Haskell:<br />
<pre><br />
*Main> removeAt 1 "abcd"<br />
('b',"acd")<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
removeAt :: Int -> [a] -> (a, [a])<br />
removeAt k xs = case back of<br />
[] -> error "removeAt: index too large"<br />
x:rest -> (x, front ++ rest)<br />
where (front, back) = splitAt k xs<br />
</haskell><br />
<br />
Simply use the <hask>splitAt</hask> to split after k elements.<br />
If the original list has fewer than k+1 elements, the second list will be empty, and there will be no element to extract.<br />
Note that the Prolog and Lisp versions treat 1 as the first element in the list, and the Lisp version appends NIL elements to the end of the list if k is greater than the list length.<br />
<br />
or <br />
<br />
<haskell><br />
removeAt n xs = (xs!!n,take n xs ++ drop (n+1) xs)<br />
</haskell><br />
<br />
[[Category:Tutorials]]</div>Chrychenghttps://wiki.haskell.org/index.php?title=99_questions/1_to_10&diff=1555899 questions/1 to 102007-09-13T12:29:01Z<p>Chrycheng: Corrected reference to group function in library. Also, removed claim of having a solution using span.</p>
<hr />
<div>__NOTOC__<br />
<br />
This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems] and [http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html Ninety-Nine Lisp Problems].<br />
<br />
If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in lisp>,<example in Haskell>,<solution in haskell> and <description of implementation> fields. <br />
<br />
== Problem 1 ==<br />
<br />
(*) Find the last box of a list.<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-last '(a b c d))<br />
(D)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myLast [1,2,3,4]<br />
[4]<br />
Prelude> myLast ['x','y','z']<br />
"z"<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
myLast :: [a] -> [a]<br />
myLast [x] = [x]<br />
myLast (_:xs) = myLast xs<br />
</haskell><br />
<br />
Haskell also provides the function <hask>last</hask>.<br />
<br />
== Problem 2 ==<br />
<br />
(*) Find the last but one box of a list.<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-but-last '(a b c d))<br />
(C D)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myButLast [1,2,3,4]<br />
[3,4]<br />
Prelude> myButLast ['a'..'z']<br />
"yz"<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
myButLast :: [a] -> [a]<br />
myButLast list = drop ((length list) - 2) list<br />
</haskell><br />
<br />
This simply drops all the but last two elements of a list.<br />
<br />
Some other options:<br />
<haskell><br />
myButLast = reverse . take 2 . reverse<br />
</haskell><br />
or<br />
<haskell><br />
myButLast list = snd $ splitAt (length list - 2) list<br />
</haskell><br />
or<br />
<haskell><br />
myButLast = last . liftM2 (zipWith const) tails (drop 1)<br />
</haskell><br />
or<br />
<haskell><br />
myButLast [a, b] = [a, b]<br />
myButLast (_ : xs) = myButLast xs<br />
</haskell><br />
(I'm very new to Haskell but this last one definitely seems to work -- bakert.)<br />
<br />
Remark:<br />
The Lisp solution is actually wrong, it should not be the last two elements; a correct Haskell solution is:<br />
<haskell><br />
myButLast = last . init<br />
Prelude> myButLast ['a'..'z']<br />
'y'<br />
</haskell><br />
See also the solution to problem 2 in the Prolog list.<br />
<br />
== Problem 3 ==<br />
<br />
(*) Find the K'th element of a list. The first element in the list is number 1.<br />
<br />
Example:<br />
<br />
<pre><br />
* (element-at '(a b c d e) 3)<br />
C<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> elementAt [1,2,3] 2<br />
2<br />
Prelude> elementAt "haskell" 5<br />
'e'<br />
</haskell><br />
<br />
Solution:<br />
<br />
This is (almost) the infix operator !! in Prelude, which is defined as:<br />
<br />
<haskell><br />
(!!) :: [a] -> Int -> a<br />
(x:_) !! 0 = x<br />
(_:xs) !! n = xs !! (n-1)<br />
</haskell><br />
<br />
Except this doesn't quite work, because !! is zero-indexed, and element-at should be one-indexed. So:<br />
<br />
<haskell><br />
elementAt :: [a] -> Int -> a<br />
elementAt list i = list !! (i-1)<br />
</haskell><br />
<br />
== Problem 4 ==<br />
<br />
(*) Find the number of elements of a list.<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myLength [123, 456, 789]<br />
3<br />
Prelude> myLength "Hello, world!"<br />
13<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
myLength :: [a] -> Int<br />
myLength [] = 0<br />
myLength (_:l) = 1 + myLength l<br />
</haskell><br />
<br />
This is <hask>length</hask> in <hask>Prelude</hask>.<br />
<br />
== Problem 5 ==<br />
<br />
(*) Reverse a list.<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> reverse "A man, a plan, a canal, panama!"<br />
"!amanap ,lanac a ,nalp a ,nam A"<br />
Prelude> reverse [1,2,3,4]<br />
[4,3,2,1]<br />
</haskell><br />
<br />
Solution: (defined in Prelude)<br />
<br />
<haskell><br />
reverse :: [a] -> [a]<br />
reverse = foldl (flip (:)) []<br />
</haskell><br />
<br />
The standard definition is concise, but not very readable. Another way to define reverse is:<br />
<br />
<haskell><br />
reverse :: [a] -> [a]<br />
reverse [] = []<br />
reverse (x:xs) = reverse xs ++ [x]<br />
</haskell><br />
<br />
However this definition is more wasteful than the one in Prelude as it repeatedly reconses the result as it is accumulated. The following variation avoids that, and thus computationally closer to the Prelude version.<br />
<br />
<haskell><br />
reverse :: [a] -> [a]<br />
reverse list = reverse' list []<br />
where<br />
reverse' [] reversed = reversed<br />
reverse' (x:xs) reversed = reverse' xs (x:reversed)<br />
</haskell> <br />
<br />
== Problem 6 ==<br />
<br />
(*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
*Main> isPalindrome [1,2,3]<br />
False<br />
*Main> isPalindrome "madamimadam"<br />
True<br />
*Main> isPalindrome [1,2,4,8,16,8,4,2,1]<br />
True<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
isPalindrome :: (Eq a) => [a] -> Bool<br />
isPalindrome xs = xs == (reverse xs)<br />
</haskell><br />
<br />
== Problem 7 ==<br />
<br />
(**) Flatten a nested list structure.<br />
<br />
Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-flatten '(a (b (c d) e)))<br />
(A B C D E)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
*Main> flatten (Elem 5)<br />
[5]<br />
*Main> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])<br />
[1,2,3,4,5]<br />
*Main> flatten (List [])<br />
[]<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
data NestedList a = Elem a | List [NestedList a]<br />
<br />
flatten :: NestedList a -> [a]<br />
flatten (Elem x) = [x]<br />
flatten (List x) = concatMap flatten x<br />
</haskell><br />
<br />
We have to define a new data type, because lists in Haskell are homogeneous.<br />
[1, [2, [3, 4], 5]] is a type error. Therefore, we must have a way of<br />
representing a list that may (or may not) be nested.<br />
<br />
Our NestedList datatype is either a single element of some type (Elem a), or a<br />
list of NestedLists of the same type. (List [NestedList a]). <br />
<br />
== Problem 8 ==<br />
<br />
(**) Eliminate consecutive duplicates of list elements.<br />
<br />
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.<br />
<br />
<pre><br />
Example:<br />
* (compress '(a a a a b c c a a d e e e e))<br />
(A B C A D E)<br />
<br />
Example in Haskell:<br />
*Main> compress ['a','a','a','a','b','c','c','a','a','d','e','e','e','e']<br />
['a','b','c','a','d','e']<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
compress :: Eq a => [a] -> [a]<br />
compress = map head . group<br />
</haskell><br />
<br />
We simply group equal values together (group), then take the head of each. <br />
Note that (with GHC) we must give an explicit type to ''compress'' otherwise we get:<br />
<br />
<haskell><br />
Ambiguous type variable `a' in the constraint:<br />
`Eq a'<br />
arising from use of `group' <br />
Possible cause: the monomorphism restriction applied to the following:<br />
compress :: [a] -> [a]<br />
Probable fix: give these definition(s) an explicit type signature<br />
or use -fno-monomorphism-restriction<br />
</haskell><br />
<br />
We can circumvent the monomorphism restriction by writing ''compress'' this way (See: section 4.5.4 of [http://haskell.org/onlinereport the report]):<br />
<br />
<haskell>compress xs = map head $ group xs</haskell><br />
<br />
An alternative solution is<br />
<br />
<haskell><br />
compress [] = []<br />
compress [a] = [a]<br />
compress (x : y : xs) = (if x == y then [] else [x]) ++ compress (y : xs)<br />
</haskell><br />
<br />
== Problem 9 ==<br />
<br />
(**) Pack consecutive duplicates of list elements into sublists.<br />
If a list contains repeated elements they should be placed in separate sublists.<br />
<br />
<pre><br />
Example:<br />
* (pack '(a a a a b c c a a d e e e e))<br />
((A A A A) (B) (C C) (A A) (D) (E E E E))<br />
<example in lisp><br />
<br />
Example in Haskell:<br />
*Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']<br />
["aaaa","b","cc","aa","d","eeee"]<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
pack (x:xs) = let (first,rest) = span (==x) xs<br />
in (x:first) : pack rest<br />
pack [] = []<br />
</haskell><br />
<br />
This is implemented as <hask>group</hask> in <hask>Data.List</hask>.<br />
<br />
== Problem 10 ==<br />
<br />
(*) Run-length encoding of a list.<br />
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.<br />
<br />
Example:<br />
<pre><br />
* (encode '(a a a a b c c a a d e e e e))<br />
((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))<br />
</pre><br />
<br />
Example in Haskell:<br />
<pre><br />
encode "aaaabccaadeeee"<br />
[(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')]<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
encode xs = map (\x -> (length x,head x)) (group xs)<br />
</haskell><br />
<br />
which can also be expressed as a list comprehension:<br />
<br />
<haskell><br />
[(length x, head x) | x <- group xs]<br />
</haskell><br />
<br />
Or writing it [[Pointfree]]:<br />
<br />
<haskell><br />
encode :: Eq a => [a] -> [(Int, a)]<br />
encode = map (\x -> (length x, head x)) . group<br />
</haskell><br />
<br />
Or (ab)using the "&&&" arrow operator for tuples:<br />
<br />
<haskell><br />
encode :: Eq a => [a] -> [(Int, a)]<br />
encode xs = map (length &&& head) $ group xs<br />
</haskell><br />
[[Category:Tutorials]]</div>Chrychenghttps://wiki.haskell.org/index.php?title=99_questions/1_to_10&diff=1555099 questions/1 to 102007-09-12T13:06:04Z<p>Chrycheng: Revised problem 4 example to differentiate the required solution from the Prelude function.</p>
<hr />
<div>__NOTOC__<br />
<br />
This is part of [[H-99:_Ninety-Nine_Haskell_Problems|Ninety-Nine Haskell Problems]], based on [https://prof.ti.bfh.ch/hew1/informatik3/prolog/p-99/ Ninety-Nine Prolog Problems] and [http://www.ic.unicamp.br/~meidanis/courses/mc336/2006s2/funcional/L-99_Ninety-Nine_Lisp_Problems.html Ninety-Nine Lisp Problems].<br />
<br />
If you want to work on one of these, put your name in the block so we know someone's working on it. Then, change n in your block to the appropriate problem number, and fill in the <Problem description>,<example in lisp>,<example in Haskell>,<solution in haskell> and <description of implementation> fields. <br />
<br />
== Problem 1 ==<br />
<br />
(*) Find the last box of a list.<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-last '(a b c d))<br />
(D)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myLast [1,2,3,4]<br />
[4]<br />
Prelude> myLast ['x','y','z']<br />
"z"<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
myLast :: [a] -> [a]<br />
myLast [x] = [x]<br />
myLast (_:xs) = myLast xs<br />
</haskell><br />
<br />
Haskell also provides the function <hask>last</hask>.<br />
<br />
== Problem 2 ==<br />
<br />
(*) Find the last but one box of a list.<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-but-last '(a b c d))<br />
(C D)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myButLast [1,2,3,4]<br />
[3,4]<br />
Prelude> myButLast ['a'..'z']<br />
"yz"<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
myButLast :: [a] -> [a]<br />
myButLast list = drop ((length list) - 2) list<br />
</haskell><br />
<br />
This simply drops all the but last two elements of a list.<br />
<br />
Some other options:<br />
<haskell><br />
myButLast = reverse . take 2 . reverse<br />
</haskell><br />
or<br />
<haskell><br />
myButLast list = snd $ splitAt (length list - 2) list<br />
</haskell><br />
or<br />
<haskell><br />
myButLast = last . liftM2 (zipWith const) tails (drop 1)<br />
</haskell><br />
or<br />
<haskell><br />
myButLast [a, b] = [a, b]<br />
myButLast (_ : xs) = myButLast xs<br />
</haskell><br />
(I'm very new to Haskell but this last one definitely seems to work -- bakert.)<br />
<br />
Remark:<br />
The Lisp solution is actually wrong, it should not be the last two elements; a correct Haskell solution is:<br />
<haskell><br />
myButLast = last . init<br />
Prelude> myButLast ['a'..'z']<br />
'y'<br />
</haskell><br />
See also the solution to problem 2 in the Prolog list.<br />
<br />
== Problem 3 ==<br />
<br />
(*) Find the K'th element of a list. The first element in the list is number 1.<br />
<br />
Example:<br />
<br />
<pre><br />
* (element-at '(a b c d e) 3)<br />
C<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> elementAt [1,2,3] 2<br />
2<br />
Prelude> elementAt "haskell" 5<br />
'e'<br />
</haskell><br />
<br />
Solution:<br />
<br />
This is (almost) the infix operator !! in Prelude, which is defined as:<br />
<br />
<haskell><br />
(!!) :: [a] -> Int -> a<br />
(x:_) !! 0 = x<br />
(_:xs) !! n = xs !! (n-1)<br />
</haskell><br />
<br />
Except this doesn't quite work, because !! is zero-indexed, and element-at should be one-indexed. So:<br />
<br />
<haskell><br />
elementAt :: [a] -> Int -> a<br />
elementAt list i = list !! (i-1)<br />
</haskell><br />
<br />
== Problem 4 ==<br />
<br />
(*) Find the number of elements of a list.<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> myLength [123, 456, 789]<br />
3<br />
Prelude> myLength "Hello, world!"<br />
13<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
myLength :: [a] -> Int<br />
myLength [] = 0<br />
myLength (_:l) = 1 + myLength l<br />
</haskell><br />
<br />
This is <hask>length</hask> in <hask>Prelude</hask>.<br />
<br />
== Problem 5 ==<br />
<br />
(*) Reverse a list.<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
Prelude> reverse "A man, a plan, a canal, panama!"<br />
"!amanap ,lanac a ,nalp a ,nam A"<br />
Prelude> reverse [1,2,3,4]<br />
[4,3,2,1]<br />
</haskell><br />
<br />
Solution: (defined in Prelude)<br />
<br />
<haskell><br />
reverse :: [a] -> [a]<br />
reverse = foldl (flip (:)) []<br />
</haskell><br />
<br />
The standard definition is concise, but not very readable. Another way to define reverse is:<br />
<br />
<haskell><br />
reverse :: [a] -> [a]<br />
reverse [] = []<br />
reverse (x:xs) = reverse xs ++ [x]<br />
</haskell><br />
<br />
However this definition is more wasteful than the one in Prelude as it repeatedly reconses the result as it is accumulated. The following variation avoids that, and thus computationally closer to the Prelude version.<br />
<br />
<haskell><br />
reverse :: [a] -> [a]<br />
reverse list = reverse' list []<br />
where<br />
reverse' [] reversed = reversed<br />
reverse' (x:xs) reversed = reverse' xs (x:reversed)<br />
</haskell> <br />
<br />
== Problem 6 ==<br />
<br />
(*) Find out whether a list is a palindrome. A palindrome can be read forward or backward; e.g. (x a m a x).<br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
*Main> isPalindrome [1,2,3]<br />
False<br />
*Main> isPalindrome "madamimadam"<br />
True<br />
*Main> isPalindrome [1,2,4,8,16,8,4,2,1]<br />
True<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
isPalindrome :: (Eq a) => [a] -> Bool<br />
isPalindrome xs = xs == (reverse xs)<br />
</haskell><br />
<br />
== Problem 7 ==<br />
<br />
(**) Flatten a nested list structure.<br />
<br />
Transform a list, possibly holding lists as elements into a `flat' list by replacing each list with its elements (recursively).<br />
<br />
Example:<br />
<br />
<pre><br />
* (my-flatten '(a (b (c d) e)))<br />
(A B C D E)<br />
</pre><br />
<br />
Example in Haskell:<br />
<br />
<haskell><br />
*Main> flatten (Elem 5)<br />
[5]<br />
*Main> flatten (List [Elem 1, List [Elem 2, List [Elem 3, Elem 4], Elem 5]])<br />
[1,2,3,4,5]<br />
*Main> flatten (List [])<br />
[]<br />
</haskell><br />
<br />
Solution:<br />
<br />
<haskell><br />
data NestedList a = Elem a | List [NestedList a]<br />
<br />
flatten :: NestedList a -> [a]<br />
flatten (Elem x) = [x]<br />
flatten (List x) = concatMap flatten x<br />
</haskell><br />
<br />
We have to define a new data type, because lists in Haskell are homogeneous.<br />
[1, [2, [3, 4], 5]] is a type error. Therefore, we must have a way of<br />
representing a list that may (or may not) be nested.<br />
<br />
Our NestedList datatype is either a single element of some type (Elem a), or a<br />
list of NestedLists of the same type. (List [NestedList a]). <br />
<br />
== Problem 8 ==<br />
<br />
(**) Eliminate consecutive duplicates of list elements.<br />
<br />
If a list contains repeated elements they should be replaced with a single copy of the element. The order of the elements should not be changed.<br />
<br />
<pre><br />
Example:<br />
* (compress '(a a a a b c c a a d e e e e))<br />
(A B C A D E)<br />
<br />
Example in Haskell:<br />
*Main> compress ['a','a','a','a','b','c','c','a','a','d','e','e','e','e']<br />
['a','b','c','a','d','e']<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
compress :: Eq a => [a] -> [a]<br />
compress = map head . group<br />
</haskell><br />
<br />
We simply group equal values together (group), then take the head of each. <br />
Note that (with GHC) we must give an explicit type to ''compress'' otherwise we get:<br />
<br />
<haskell><br />
Ambiguous type variable `a' in the constraint:<br />
`Eq a'<br />
arising from use of `group' <br />
Possible cause: the monomorphism restriction applied to the following:<br />
compress :: [a] -> [a]<br />
Probable fix: give these definition(s) an explicit type signature<br />
or use -fno-monomorphism-restriction<br />
</haskell><br />
<br />
We can circumvent the monomorphism restriction by writing ''compress'' this way (See: section 4.5.4 of [http://haskell.org/onlinereport the report]):<br />
<br />
<haskell>compress xs = map head $ group xs</haskell><br />
<br />
An alternative solution is<br />
<br />
<haskell><br />
compress [] = []<br />
compress [a] = [a]<br />
compress (x : y : xs) = (if x == y then [] else [x]) ++ compress (y : xs)<br />
</haskell><br />
<br />
== Problem 9 ==<br />
<br />
(**) Pack consecutive duplicates of list elements into sublists.<br />
If a list contains repeated elements they should be placed in separate sublists.<br />
<br />
<pre><br />
Example:<br />
* (pack '(a a a a b c c a a d e e e e))<br />
((A A A A) (B) (C C) (A A) (D) (E E E E))<br />
<example in lisp><br />
<br />
Example in Haskell:<br />
*Main> pack ['a', 'a', 'a', 'a', 'b', 'c', 'c', 'a', 'a', 'd', 'e', 'e', 'e', 'e']<br />
["aaaa","b","cc","aa","d","eeee"]<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
pack (x:xs) = let (first,rest) = span (==x) xs<br />
in (x:first) : pack rest<br />
pack [] = []<br />
</haskell><br />
<br />
'group' is also in the Prelude, here's an implementation using 'span'.<br />
<br />
== Problem 10 ==<br />
<br />
(*) Run-length encoding of a list.<br />
Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as lists (N E) where N is the number of duplicates of the element E.<br />
<br />
Example:<br />
<pre><br />
* (encode '(a a a a b c c a a d e e e e))<br />
((4 A) (1 B) (2 C) (2 A) (1 D)(4 E))<br />
</pre><br />
<br />
Example in Haskell:<br />
<pre><br />
encode "aaaabccaadeeee"<br />
[(4,'a'),(1,'b'),(2,'c'),(2,'a'),(1,'d'),(4,'e')]<br />
</pre><br />
<br />
Solution:<br />
<haskell><br />
encode xs = map (\x -> (length x,head x)) (group xs)<br />
</haskell><br />
<br />
which can also be expressed as a list comprehension:<br />
<br />
<haskell><br />
[(length x, head x) | x <- group xs]<br />
</haskell><br />
<br />
Or writing it [[Pointfree]]:<br />
<br />
<haskell><br />
encode :: Eq a => [a] -> [(Int, a)]<br />
encode = map (\x -> (length x, head x)) . group<br />
</haskell><br />
<br />
Or (ab)using the "&&&" arrow operator for tuples:<br />
<br />
<haskell><br />
encode :: Eq a => [a] -> [(Int, a)]<br />
encode xs = map (length &&& head) $ group xs<br />
</haskell><br />
[[Category:Tutorials]]</div>Chrychenghttps://wiki.haskell.org/index.php?title=Talk:99_questions/1_to_10&diff=15549Talk:99 questions/1 to 102007-09-12T12:02:16Z<p>Chrycheng: </p>
<hr />
<div>==Does the problem 1 example need correction?==<br />
<br />
The problem refers us to <hask>last</hask> as a <hask>Prelude</hask> function providing the same functionality. However, <hask>last</hask> has type <hask>[a] -> a</hask> which differs from the Lisp example's type <hask>[a] -> [a]</hask>. Should we revise the example or should we rephrase the reference to <hask>last</hask> to highlight the difference?<br />
<br />
[[User:Chrycheng|Chrycheng]] 12:02, 12 September 2007 (UTC)</div>Chrycheng