-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathList.hs
660 lines (580 loc) · 12.4 KB
/
List.hs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE NoImplicitPrelude #-}
-- + Complete the 10 exercises below by filling out the function bodies.
-- Replace the function bodies (error "todo: ...") with an appropriate
-- solution.
-- + These exercises may be done in any order, however:
-- Exercises are generally increasing in difficulty, though some people may find later exercise easier.
-- + Bonus for using the provided functions or for using one exercise solution to help solve another.
-- + Approach with your best available intuition; just dive in and do what you can!
module List where
import qualified Control.Applicative as A
import qualified Control.Monad as M
import Core
import qualified Numeric as N
import Optional (Optional (..))
import qualified Optional as O
import qualified System.Environment as E
import qualified Prelude as P
-- $setup
-- >>> import Test.QuickCheck
-- >>> import Course.Core(even, id, const)
-- >>> import qualified Prelude as P(fmap, foldr)
-- >>> instance Arbitrary a => Arbitrary (List a) where arbitrary = P.fmap ((P.foldr (:.) Nil) :: ([a] -> List a)) arbitrary
-- BEGIN Helper functions and data types
-- The custom list type
data List t
= Nil
| t :. List t
deriving stock (Eq, Ord)
-- Right-associative
infixr 5 :.
instance (Show t) => Show (List t) where
show = show . hlist
-- The list of integers from zero to infinity.
infinity ::
List Integer
infinity =
let inf x = x :. inf (x + 1)
in inf 0
-- functions over List that you may consider using
foldRight :: (a -> b -> b) -> b -> List a -> b
foldRight _ b Nil = b
foldRight f b (h :. t) = f h (foldRight f b t)
foldLeft :: (b -> a -> b) -> b -> List a -> b
foldLeft _ b Nil = b
foldLeft f b (h :. t) = let b' = f b h in b' `seq` foldLeft f b' t
-- END Helper functions and data types
-- | Returns the head of the list or the given default.
--
-- >>> headOr 3 (1 :. 2 :. Nil)
-- 1
--
-- >>> headOr 3 Nil
-- 3
--
-- prop> \x -> x `headOr` infinity == 0
--
-- prop> \x -> x `headOr` Nil == x
headOr :: a -> List a -> a
headOr a Nil = a
headOr _ (x :. _) = x
-- | The product of the elements of a list.
--
-- >>> product Nil
-- 1
--
-- >>> product (1 :. 2 :. 3 :. Nil)
-- 6
--
-- >>> product (1 :. 2 :. 3 :. 4 :. Nil)
-- 24
product :: List Int -> Int
product = foldLeft (*) 1
-- | Sum the elements of the list.
--
-- >>> sum (1 :. 2 :. 3 :. Nil)
-- 6
--
-- >>> sum (1 :. 2 :. 3 :. 4 :. Nil)
-- 10
--
-- prop> \x -> foldLeft (-) (sum x) x == 0
sum :: List Int -> Int
sum = foldLeft (+) 0
-- | Return the length of the list.
--
-- >>> length (1 :. 2 :. 3 :. Nil)
-- 3
--
-- prop> \x -> sum (map (const 1) x) == length x
length :: List a -> Int
length = sum . map (const 1)
-- | Map the given function on each element of the list.
--
-- >>> map (+10) (1 :. 2 :. 3 :. Nil)
-- [11,12,13]
--
-- prop> \x -> headOr x (map (+1) infinity) == 1
--
-- prop> \x -> map id x == x
map :: (a -> b) -> List a -> List b
map f = foldRight ((:.) . f) Nil
-- | Return elements satisfying the given predicate.
--
-- >>> filter even (1 :. 2 :. 3 :. 4 :. 5 :. Nil)
-- [2,4]
--
-- prop> \x -> headOr x (filter (const True) infinity) == 0
--
-- prop> \x -> filter (const True) x == x
--
-- prop> \x -> filter (const False) x == Nil
filter :: (a -> Bool) -> List a -> List a
filter f = foldRight g Nil
where
g x acc = if f x then x :. acc else acc
-- | Append two lists to a new list.
--
-- >>> (1 :. 2 :. 3 :. Nil) ++ (4 :. 5 :. 6 :. Nil)
-- [1,2,3,4,5,6]
--
-- prop> \x -> headOr x (Nil ++ infinity) == 0
--
-- prop> \x -> headOr x (y ++ infinity) == headOr 0 y
--
-- prop> \x -> (x ++ y) ++ z == x ++ (y ++ z)
--
-- prop> \x -> x ++ Nil == x
(++) :: List a -> List a -> List a
(++) = flip (foldRight (:.))
infixr 5 ++
-- | Flatten a list of lists to a list.
--
-- >>> flatten ((1 :. 2 :. 3 :. Nil) :. (4 :. 5 :. 6 :. Nil) :. (7 :. 8 :. 9 :. Nil) :. Nil)
-- [1,2,3,4,5,6,7,8,9]
--
-- prop> \x -> headOr x (flatten (infinity :. y :. Nil)) == 0
--
-- prop> \x -> headOr x (flatten (y :. infinity :. Nil)) == headOr 0 y
--
-- prop> \x -> sum (map length x) == length (flatten x)
flatten :: List (List a) -> List a
flatten = flatMap id
-- | Map a function then flatten to a list.
--
-- >>> flatMap (\x -> x :. x + 1 :. x + 2 :. Nil) (1 :. 2 :. 3 :. Nil)
-- [1,2,3,2,3,4,3,4,5]
--
-- prop> \x -> headOr x (flatMap id (infinity :. y :. Nil)) == 0
--
-- prop> \x -> headOr x (flatMap id (y :. infinity :. Nil)) == headOr 0 y
--
-- prop> \x -> flatMap id (x :: List (List Int)) == flatten x
flatMap :: (a -> List b) -> List a -> List b
flatMap f = foldRight ((++) . f) Nil
-- | Flatten a list of lists to a list (again).
-- HOWEVER, this time use the /flatMap/ function that you just wrote.
--
-- prop> \x -> let types = x :: List (List Int) in flatten x == flattenAgain x
flattenAgain :: List (List a) -> List a
flattenAgain = flatten
-- | Convert a list of optional values to an optional list of values.
--
-- * If the list contains all `Full` values,
-- then return `Full` list of values.
--
-- * If the list contains one or more `Empty` values,
-- then return `Empty`.
--
-- >>> seqOptional (Full 1 :. Full 10 :. Nil)
-- Full [1, 10]
--
-- >>> seqOptional Nil
-- Full []
--
-- >>> seqOptional (Full 1 :. Full 10 :. Empty :. Nil)
-- Empty
--
-- >>> seqOptional (Empty :. map Full infinity)
-- Empty
seqOptional :: List (Optional a) -> Optional (List a)
seqOptional Nil = Full Nil
-- (:.) P.<$> x P.<*> seqOptional xs
seqOptional (x :. xs) = O.twiceOptional (:.) x (seqOptional xs)
-- | Find the first element in the list matching the predicate.
--
-- >>> find even (1 :. 3 :. 5 :. Nil)
-- Empty
--
-- >>> find even Nil
-- Empty
--
-- >>> find even (1 :. 2 :. 3 :. 5 :. Nil)
-- Full 2
--
-- >>> find even (1 :. 2 :. 3 :. 4 :. 5 :. Nil)
-- Full 2
--
-- >>> find (const True) infinity
-- Full 0
find :: (a -> Bool) -> List a -> Optional a
find _ Nil = Empty
find f (x :. xs) = if f x then Full x else find f xs
-- | Determine if the length of the given list is greater than 4.
--
-- >>> lengthGT4 (1 :. 3 :. 5 :. Nil)
-- False
--
-- >>> lengthGT4 Nil
-- False
--
-- >>> lengthGT4 (1 :. 2 :. 3 :. 4 :. 5 :. Nil)
-- True
--
-- >>> lengthGT4 infinity
-- True
lengthGT4 :: List a -> Bool
lengthGT4 (_ :. _ :. _ :. _ :. _ :. _) = True
lengthGT4 _ = False
-- | Reverse a list.
--
-- >>> reverse Nil
-- []
--
-- >>> take 1 (reverse (reverse largeList))
-- [1]
--
-- prop> \x -> let types = x :: List Int in reverse x ++ reverse y == reverse (y ++ x)
--
-- prop> \x -> let types = x :: Int in reverse (x :. Nil) == x :. Nil
reverse :: List a -> List a
reverse = foldLeft (flip (:.)) Nil
-- | Produce an infinite `List` that seeds with the given value at its head,
-- then runs the given function for subsequent elements
--
-- >>> let (x:.y:.z:.w:._) = produce (+1) 0 in [x,y,z,w]
-- [0,1,2,3]
--
-- >>> let (x:.y:.z:.w:._) = produce (*2) 1 in [x,y,z,w]
-- [1,2,4,8]
produce :: (a -> a) -> a -> List a
produce f x = xs where xs = x :. map f xs
-- | Do anything other than reverse a list.
-- Is it even possible?
--
-- >>> notReverse Nil
-- []
--
-- prop> \x y -> let types = x :: List Int in notReverse x ++ notReverse y == notReverse (y ++ x)
--
-- prop> \x -> let types = x :: Int in notReverse (x :. Nil) == x :. Nil
notReverse :: List a -> List a
notReverse = error "todo: Is it even possible?"
---- End of list exercises
largeList ::
List Int
largeList =
listh [1 .. 50000]
hlist ::
List a ->
[a]
hlist =
foldRight (:) []
listh ::
[a] ->
List a
listh =
P.foldr (:.) Nil
putStr ::
Chars ->
IO ()
putStr =
P.putStr . hlist
putStrLn ::
Chars ->
IO ()
putStrLn =
P.putStrLn . hlist
readFile ::
FilePath ->
IO Chars
readFile =
P.fmap listh . P.readFile . hlist
writeFile ::
FilePath ->
Chars ->
IO ()
writeFile n s =
P.writeFile (hlist n) (hlist s)
getLine ::
IO Chars
getLine =
P.fmap listh P.getLine
getArgs ::
IO (List Chars)
getArgs =
P.fmap (listh . P.fmap listh) E.getArgs
isPrefixOf ::
(Eq a) =>
List a ->
List a ->
Bool
isPrefixOf Nil _ =
True
isPrefixOf _ Nil =
False
isPrefixOf (x :. xs) (y :. ys) =
x == y && isPrefixOf xs ys
isEmpty ::
List a ->
Bool
isEmpty Nil =
True
isEmpty (_ :. _) =
False
span ::
(a -> Bool) ->
List a ->
(List a, List a)
span p x =
(takeWhile p x, dropWhile p x)
break ::
(a -> Bool) ->
List a ->
(List a, List a)
break p =
span (not . p)
dropWhile ::
(a -> Bool) ->
List a ->
List a
dropWhile _ Nil =
Nil
dropWhile p xs@(x :. xs') =
if p x
then
dropWhile p xs'
else
xs
takeWhile ::
(a -> Bool) ->
List a ->
List a
takeWhile _ Nil =
Nil
takeWhile p (x :. xs) =
if p x
then
x :. takeWhile p xs
else
Nil
zip ::
List a ->
List b ->
List (a, b)
zip =
zipWith (,)
zipWith ::
(a -> b -> c) ->
List a ->
List b ->
List c
zipWith f (a :. as) (b :. bs) =
f a b :. zipWith f as bs
zipWith _ _ _ =
Nil
unfoldr ::
(a -> Optional (b, a)) ->
a ->
List b
unfoldr f a =
case f a of
Full (b, a') -> b :. unfoldr f a'
Empty -> Nil
lines ::
Chars ->
List Chars
lines =
listh . P.fmap listh . P.lines . hlist
unlines ::
List Chars ->
Chars
unlines =
listh . P.unlines . hlist . map hlist
words ::
Chars ->
List Chars
words =
listh . P.fmap listh . P.words . hlist
unwords ::
List Chars ->
Chars
unwords =
listh . P.unwords . hlist . map hlist
listOptional ::
(a -> Optional b) ->
List a ->
List b
listOptional _ Nil =
Nil
listOptional f (h :. t) =
let r = listOptional f t
in case f h of
Empty -> r
Full q -> q :. r
any ::
(a -> Bool) ->
List a ->
Bool
any p =
foldRight ((||) . p) False
all ::
(a -> Bool) ->
List a ->
Bool
all p =
foldRight ((&&) . p) True
or ::
List Bool ->
Bool
or =
any id
and ::
List Bool ->
Bool
and =
all id
elem ::
(Eq a) =>
a ->
List a ->
Bool
elem x =
any (== x)
notElem ::
(Eq a) =>
a ->
List a ->
Bool
notElem x =
all (/= x)
permutations ::
List a -> List (List a)
permutations xs0 =
let perms Nil _ =
Nil
perms (t :. ts) is =
let interleave' _ Nil r =
(ts, r)
interleave' f (y :. ys) r =
let (us, zs) = interleave' (f . (y :.)) ys r
in (y :. us, f (t :. y :. us) :. zs)
in foldRight (\xs -> snd . interleave' id xs) (perms ts (t :. is)) (permutations is)
in xs0 :. perms xs0 Nil
intersectBy ::
(a -> b -> Bool) ->
List a ->
List b ->
List a
intersectBy e xs ys =
filter (\x -> any (e x) ys) xs
take ::
(Num n, Ord n) =>
n ->
List a ->
List a
take n _
| n <= 0 =
Nil
take _ Nil =
Nil
take n (x :. xs) =
x :. take (n - 1) xs
drop ::
(Num n, Ord n) =>
n ->
List a ->
List a
drop n xs
| n <= 0 =
xs
drop _ Nil =
Nil
drop n (_ :. xs) =
drop (n - 1) xs
repeat ::
a ->
List a
repeat x =
x :. repeat x
replicate ::
(Num n, Ord n) =>
n ->
a ->
List a
replicate n x =
take n (repeat x)
reads ::
(P.Read a) =>
Chars ->
Optional (a, Chars)
reads s =
case P.reads (hlist s) of
[] -> Empty
((a, q) : _) -> Full (a, listh q)
read ::
(P.Read a) =>
Chars ->
Optional a
read =
O.mapOptional fst . reads
readHexs ::
(Eq a, Num a) =>
Chars ->
Optional (a, Chars)
readHexs s =
case N.readHex (hlist s) of
[] -> Empty
((a, q) : _) -> Full (a, listh q)
readHex ::
(Eq a, Num a) =>
Chars ->
Optional a
readHex =
O.mapOptional fst . readHexs
-- Returns the parsed number and the remaining input.
readFloats ::
(RealFrac a) =>
Chars ->
Optional (a, Chars)
readFloats s =
case N.readSigned N.readFloat (hlist s) of
[] -> Empty
((a, q) : _) -> Full (a, listh q)
readFloat ::
(RealFrac a) =>
Chars ->
Optional a
readFloat =
O.mapOptional fst . readFloats
-- This makes `OverloadedStrings` convert a String to a List.
instance (a P.~ Char) => IsString (List a) where
-- Per https://hackage.haskell.org/package/base-4.14.1.0/docs/src/Data.String.html#line-43
fromString =
listh
type Chars =
List Char
type FilePath =
List Char
strconcat ::
[Chars] ->
P.String
strconcat =
P.concatMap hlist
stringconcat ::
[P.String] ->
P.String
stringconcat =
P.concat
show' ::
(Show a) =>
a ->
List Char
show' =
listh . show
instance P.Functor List where
fmap f =
listh . P.fmap f . hlist
instance A.Applicative List where
(<*>) =
M.ap
pure =
(:. Nil)
instance P.Monad List where
(>>=) =
flip flatMap