forked from caiorss/Functional-Programming
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUseful_Custom_Functions__Iterators_and_Operators.org
More file actions
540 lines (394 loc) · 10.5 KB
/
Copy pathUseful_Custom_Functions__Iterators_and_Operators.org
File metadata and controls
540 lines (394 loc) · 10.5 KB
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
#+INCLUDE: ../theme/style.org
#+TITLE: Useful Custom Functions/ Iterators and Operators
* Useful Custom Functions/ Iterators and Operators
This is a collection of useful short code snippets.
** Pipelining Operators
Haskell doesn't have a native Pipe operator like F# (F-Sharp) does, however
it can be defined by the user.
#+BEGIN_SRC haskell
> let (|>) x f = f x
>
> let (|>>) x f = map f x
> let (?>>) x f = filter f x
> take 3 (reverse (filter even [1..10]))
[10,8,6]
> [1..10] |> filter even |> reverse |> take 3
[10,8,6]
>
> [1..10] |>> (^2) |>> (/10) |>> (+100)
[100.1,100.4,100.9,101.6,102.5,103.6,104.9,106.4,108.1,110.0]
>
> [1..10] ?>> even
[2,4,6,8,10]
>
> [1..10] ?>> even |>> (+1)
[3,5,7,9,11]
>
>
#+END_SRC
*** Iterators
*** Pair Iterator
Definition:
#+BEGIN_SRC haskell
pairs alist = zip alist (tail alist)
#+END_SRC
The pairs iterator converts a list of elements to a new list of consecutive elements tuple.
Pseudo code:
#+BEGIN_SRC
pairs [e0, e1, e2, e3, e4 ...] ==> [(e0, e1), (e1, e2), (e3, e4) ...]
#+END_SRC
Let f be a function of two arguments:
#+BEGIN_SRC
f :: a -> a -> b
#+END_SRC
The function f can be applied to to the pairs sequence using the higher order function uncurry.
Pseudo code:
#+BEGIN_SRC
> g = uncurry(f) :: (a, a) -> b
> g (x, y) = f x y
> map uncurry(f) $ pairs [e0, e1, e2, e3, e4 ...]
> [g (e0, e1), g (e1, e2), g (e2, e3), g (e3, e4) ...]
#+END_SRC
It can be useful to calculate the distance between two points, lagged difference, growth of a time series, draw a line between each two consecutive points or apply any function to two consecutive elements.
Example: Grouping Consecutive numbers
#+BEGIN_SRC haskell
> let pairs alist = zip alist (tail alist)
> pairs [1..5]
[(1,2),(2,3),(3,4),(4,5)]
#+END_SRC
Example: Lagged Difference
Pseudo code:
#+BEGIN_SRC
lagdiff [e0, e1, e2, e3, e4 ...] ==> [(e1 - e0), (e2 - e1), (e3 - e2) ... ]
#+END_SRC
Development:
#+BEGIN_SRC haskell
> let pairs alist = zip alist (tail alist)
> :t pairs
pairs :: [b] -> [(b, b)]
> :t (-)
(-) :: Num a => a -> a -> a
> :t uncurry(-)
uncurry(-) :: Num c => (c, c) -> c
>
> (-) 20 10
10
>
> uncurry(-) (20, 10)
10
>
> uncurry(-) (10, 20)
-10
>
> uncurry(flip (-)) (10, 20)
10
>
> pairs [10.3, 20.5, 5.6, 8.23, 40.3]
[(10.3,20.5),(20.5,5.6),(5.6,8.23),(8.23,40.3)]
>
> map (uncurry ( flip (-))) $ pairs [10.3, 20.5, 5.6, 8.23, 40.3]
[10.2,-14.9,2.630000000000001,32.06999999999999]
>
> let lagdiff series = map (uncurry ( flip (-))) $ pairs series
> :t lagdiff
lagdiff :: Num b => [b] -> [b]
>
> lagdiff [10.3, 20.5, 5.6, 8.23, 40.3]
[10.2,-14.9,2.630000000000001,32.06999999999999]
>
> lagdiff [10, 30, 5, 8, 100]
[20,-25,3,92]
>
#+END_SRC
Example: Distance between points on the plane.
#+BEGIN_SRC haskell
> let pairs alist = zip alist (tail alist)
{- [(X, Y)] coordinates of points in a plane -}
> let points = [(1.0, 2.0), (3.0, 4.0), (-1.0, 5.0), (6.0, 6.0)]
> let distance (x1, y1) (x2, y2) = sqrt( (x2-x1)^2 + (y2-y1)^2 )
> let lines = pairs points
> lines
[((1.0,2.0),(3.0,4.0)),((3.0,4.0),(-1.0,5.0)),((-1.0,5.0),(6.0,6.0))]
>
> distance (1.0, 2.0) (3.0, 4.0)
2.8284271247461903
>
{- Calculate the length of each line segment -}
> map (uncurry(distance)) lines
[2.8284271247461903,4.123105625617661,7.0710678118654755]
>
> sum $ map (uncurry(distance)) lines
14.022600562229327
>
> let totalLength points = sum $ map (uncurry(distance)) $ pairs (points)
>
> totalLength points
14.022600562229327
>
#+END_SRC
*** Triples Iterator
Definition:
#+BEGIN_SRC haskell
triples alist = zip3 alist (tail alist) (tail $ tail alist)
#+END_SRC
Example:
#+BEGIN_SRC haskell
> triples [1..10]
[(1,2,3),(2,3,4),(3,4,5),(4,5,6),(5,6,7),(6,7,8),(7,8,9),(8,9,10)]
>
> :t triples
triples :: [c] -> [(c, c, c)]
>
>
#+END_SRC
*** Sliding Window Iterator
This iterator is used in Scala and it is a generalized pairs iterator.
Definition:
#+BEGIN_SRC haskell
sliding n alist = map (take n) (take (length(alist) -n + 1 ) $ iterate tail alist)
#+END_SRC
Example:
#+BEGIN_SRC haskell
> sliding 3 [1..10]
[[1,2,3],[2,3,4],[3,4,5],[4,5,6],[5,6,7],[6,7,8],[7,8,9],[8,9,10]]
> sliding 4 [1..10]
[[1,2,3,4],[2,3,4,5],[3,4,5,6],[4,5,6,7],[5,6,7,8],[6,7,8,9],[7,8,9,10]]
> sliding 5 [1..10]
[[1,2,3,4,5],[2,3,4,5,6],[3,4,5,6,7],[4,5,6,7,8],[5,6,7,8,9],[6,7,8,9,10]]
> sliding 6 [1..10]
[[1,2,3,4,5,6],[2,3,4,5,6,7],[3,4,5,6,7,8],[4,5,6,7,8,9],[5,6,7,8,9,10]]
> sliding 9 [1..10]
[[1,2,3,4,5,6,7,8,9],[2,3,4,5,6,7,8,9,10]]
>
#+END_SRC
Scala Equivalent
#+BEGIN_SRC
scala> (1 to 5).iterator.sliding(3).toList
res2: List[Seq[Int]] = List(List(1, 2, 3), List(2, 3, 4), List(3, 4, 5))
#+END_SRC
*** Enumerate Iterator
Equivalent to python enumerate.
Definition:
#+BEGIN_SRC haskell
enumerate :: [b] -> [(Int, b)]
enumerate alist = zip [0..(length(alist)-1)] alist
#+END_SRC
Example:
#+BEGIN_SRC haskell
> enumerate ['a', 'b', 'c', 'd', 'e', 'f']
[(0,'a'),(1,'b'),(2,'c'),(3,'d'),(4,'e'),(5,'f')]
> take 8 (enumerate ['a'..'z'])
[(0,'a'),(1,'b'),(2,'c'),(3,'d'),(4,'e'),(5,'f'),(6,'g'),(7,'h')]
>
#+END_SRC
*Group by length*
Definition:
#+BEGIN_SRC haskell
groupByLen n alist = filter (\a -> length(a) == n ) ( map f indexes )
where
len = length(alist)
indexes = map (\i -> n*i) [0..(div len n)]
f idx = take n (drop idx alist)
#+END_SRC
Example:
#+BEGIN_SRC haskell
> groupByLen 3 [1..15]
[[1,2,3],[4,5,6],[7,8,9],[10,11,12],[13,14,15]]
>
> groupByLen 5 [1..15]
[[1,2,3,4,5],[6,7,8,9,10],[11,12,13,14,15]]
>
> groupByLen 6 [0..20]
[[0,1,2,3,4,5],[6,7,8,9,10,11],[12,13,14,15,16,17]]
>
> groupByLen 3 ['a'..'z']
["abc","def","ghi","jkl","mno","pqr","stu","vwx"]
>
#+END_SRC
** Applying Multiples Functions
*** Applying a list of functions to the same argument.
*juxt* is a function that allows apply a list of functions of same type signature to a single argument. This is useful for numerical analysis, statistics and engineering. This function was taken from the Clojure library.
#+BEGIN_SRC haskell
juxt fs x = map ($ x) fs
#+END_SRC
Example:
#+BEGIN_SRC
> let juxt fs x = map ($ x) fs
> juxt [(*3), (+4), (/10)] 30
[90.0,34.0,3.0]
>
> let fs = juxt [(*3), (+4), (/10)]
>
> :t fs
fs :: Double -> [Double]
>
> fs 30
[90.0,34.0,3.0]
> fs 40
[120.0,44.0,4.0]
>
> map fs [10, 20, 30]
[[30.0,14.0,1.0],[60.0,24.0,2.0],[90.0,34.0,3.0]]
>
#+END_SRC
*** Applying a tuple of functions to a same argument.
The family of functions juxt2, juxt3, juxt4 allow apply tuples of functions to a single argument. This is necessary when the functions don't have the same type signature.
#+BEGIN_SRC haskell
juxt2 (f1, f2) x = (f1 x, f2 x)
juxt3 (f1, f2, f3) x = (f1 x, f2 x, f3 x)
juxt4 (f1, f2, f3, f4) x = (f1 x, f2 x, f3 x, f4 x)
juxt5 (f1, f2, f3, f4, f5) x = (f1 x, f2 x, f3 x, f4 x, f5 x)
#+END_SRC
Example:
#+BEGIN_SRC haskell
{-
This function fails in static typed language when
the functions don't have the same type signature
-}
> juxt [(>100), (+100)] 30
<interactive>:36:9:
No instance for (Num Bool) arising from the literal `100'
Possible fix: add an instance declaration for (Num Bool)
In the second argument of `(>)', namely `100'
In the expression: (> 100)
In the first argument of `juxt', namely `[(> 100), (+ 100)]'
> juxt2 ((>100), (+100)) 30
(False,130)
>
>
> let f = juxt2 ((>100), (+100))
> :t f
f :: Integer -> (Bool, Integer)
>
> f 30
(False,130)
>
> map f [10, 20, 25, 30, 100, 150]
[(False,110),(False,120),(False,125),(False,130),(False,200),(True,250)]
>
>
> juxt3 (length, maximum, minimum) [100.23, 23.23, 12.33, -123.23, -1000.23, 4000.5]
(6,4000.5,-1000.23)
>
{-
The type system fails to resolve the types in someone
cases. So when it happens the developer must make the
function types explicit.
-}
> let analytics = juxt3 (length, maximum, minimum)
>
> :t analytics
analytics :: [()] -> (Int, (), ())
>
> analytics [100.23, 23.23, 12.33, -123.23, -1000.23, 4000.5]
<interactive>:79:12:
No instance for (Fractional ()) arising from the literal `100.23'
Possible fix: add an instance declaration for (Fractional ())
In the expression: 100.23
In the first argument of `analytics', namely
`[100.23, 23.23, 12.33, - 123.23, ....]'
In the expression: analytics [100.23, 23.23, 12.33, - 123.23, ....]
> let analytics :: [Double] -> (Int, Double, Double) ; analytics = juxt3 (length, maximum, minimum)
>
> :t analytics
analytics :: [Double] -> (Int, Double, Double)
>
> analytics [100.23, 23.23, 12.33, -123.23, -1000.23, 4000.5]
(6,4000.5,-1000.23)
>
> import Data.Char
>
> let f = juxt3 (succ, pred, ord)
> :t f
f :: Char -> (Char, Char, Int)
>
> let a = map f "haskell is fun"
> a
[('i','g',104),('b','`',97),('t','r',115),('l','j',107),('f','d',101),('m','k',108),('m','k',108),('!','\US',32),('j','h',105),('t','r',115),('!','\US',32),('g','e',102),('v','t',117),('o','m',110)]
>
> unzip3 a
("ibtlfmm!jt!gvo","g`rjdkk\UShr\USetm",[104,97,115,107,101,108,108,32,105,115,32,102,117,110])
>
>
#+END_SRC
*** Control Flow Functions
*between*
#+BEGIN_SRC haskell
between a b x = a <= x && x <= b
#+END_SRC
#+BEGIN_SRC haskell
> filter (between 10 20) [23, 5, 8, 17, 24, 13, 12]
[17,13,12]
>
> filter (not . between 10 20) [23, 5, 8, 17, 24, 13, 12]
[23,5,8,24]
#+END_SRC
*ifelseDo*
Pseudo Code:
#+BEGIN_SRC
f(x) = if pred(x) == True then: fa(x) else fb(x)
#+END_SRC
#+BEGIN_SRC haskell
ifelseDo pred fa fb x = if pred x then fa x else fb x
#+END_SRC
Example: Apply the list the function (if x >10 then 10*x else x+5)
#+BEGIN_SRC haskell
> let ifelseDo pred fa fb x = if pred x then fa x else fb x
> map (ifelseDo (>10) (*4) (+5)) [-1, 2, 7, 8, 9, 10, 20, 30, 50]
[4,7,12,13,14,15,80,120,200]
> let f = ifelseDo (>10) (*4) (+5)
> f 1
6
> f 3
8
> f 5
10
>
> f 20
80
> f 30
120
λ> map f [-1, 2, 7, 8, 9, 10, 20, 30, 50]
[4,7,12,13,14,15,80,120,200]
#+END_SRC
*ifelse**
Pseudo Code:
#+BEGIN_SRC
f(x) = if pred(x) == True then: a else b
#+END_SRC
#+BEGIN_SRC haskell
ifelse pred a b x = if pred x then a else b
#+END_SRC
Example:
If x<0 set x to -1 else set to 1
#+BEGIN_SRC haskell
> let f = ifelse (<0) (-1) 1
>
> f 2
1
> f 40
1
> f (-1)
-1
> f (-10)
-1
> map f [-1, -2, 3, 4, -5, -6, 0, 2]
[-1,-1,1,1,-1,-1,1,1]
>
#+END_SRC
*ifelseEq*
Pseudo Code:
#+BEGIN_SRC
f(x) = if pred(x) == True then: a else x
#+END_SRC
#+BEGIN_SRC haskell
ifelseEq pred a x = if pred x then a else x
#+END_SRC
Example: if(x) > 10 then 30 else x
#+BEGIN_SRC haskell
> let ifelseEq pred a x = if pred x then a else x
> let f = ifelseEq (>10) 30
> map f [1, 2, 20, 10, 9, 8, 100]
[1,2,30,10,9,8,30]
>
#+END_SRC