1Functional(3)         User Contributed Perl Documentation        Functional(3)
2
3
4

NAME

6       Language::Functional - a module which makes Perl slightly more
7       functional
8

SYNOPSIS

10         use Language::Functional ':all';
11         print 'The first ten primes are: ',
12           show(take(10, filter { prime(shift) } integers)), "\n";
13

DESCRIPTION

15       Perl already contains some functional-like functions, such as "map" and
16       "grep". The purpose of this module is to add other functional-like
17       functions to Perl, such as foldl and foldr, as well as the use of
18       infinite lists.
19
20       Think as to how you would express the first ten prime numbers in a
21       simple way in your favourite programming language? So the example in
22       the synopsis is a killer app, if you will (until I think up a better
23       one ;-).
24
25       The idea is mostly based on Haskell, from which most of the functions
26       are taken. There are a couple of major omissions: currying and types.
27       Lists (and tuples) are simply Perl list references, none of this 'cons'
28       business, and strings are simple strings, not lists of characters.
29
30       The idea is to make Perl slightly more functional, rather than
31       completely replace it. Hence, this slots in very well with whatever
32       else your program may be doing, and is very Perl-ish. Other modules are
33       expected to try a much more functional approach.
34

FUNCTIONS

36       The following functions are available. (Note: these should not be
37       called as methods).
38
39       In each description, I shall give the Haskell definition (if I think it
40       would help) as well as a useful example.
41
42       show
43           Show returns a string representation of an object.  It does not
44           like infinite lists.
45
46       inc k
47           Increases the value passed by 1.
48
49             $x = inc 2; # 3
50
51           In Haskell:
52
53             inc          :: a -> a
54             inc k         = 1 + k
55
56       double k
57           Doubles the passed value.
58
59             $x = double 3; # 6
60
61           In Haskell:
62
63             double         :: a -> a
64             double k        = k * 2
65
66       square k
67           Returns the square of the passed value. eg:
68
69             $x = square 3; # 9
70
71           In Haskell:
72
73             square          :: a -> a
74             square k         = k * k
75
76       gcd x y
77           Returns the greatest common denominator of two numbers. eg:
78
79             $x = gcd(144, 1024); # 16
80
81           In Haskell:
82
83             gcd :: Integral a => a -> a -> a
84             gcd 0 0 = error "gcd 0 0 is undefined"
85             gcd x y = gcd' (abs x) (abs y)
86                       where gcd' x 0 = x
87                       gcd' x y = gcd' y (x `rem` y)
88
89       lcm x y
90           Returns the lowest common multiple of two numbers.  eg:
91
92             $x = lcm(144, 1024); # 9216
93
94           In Haskell:
95
96             lcm            :: (Integral a) => a -> a -> a
97             lcm _ 0         = 0
98             lcm 0 _         = 0
99             lcm x y         = abs ((x `quot` gcd x y) * y)
100
101       id x
102           The identity function - simply returns the argument.  eg:
103
104             $x = id([1..6]); # [1, 2, 3, 4, 5, 6].
105
106           In Haskell:
107
108             id             :: a -> a
109             id x            = x
110
111       const k _
112           Returns the first argument of 2 arguments. eg:
113
114             $x = const(4, 5); # 4
115
116           In Haskell:
117
118             const          :: a -> b -> a
119             const k _       = k
120
121       flip f
122           Given a function, flips the two arguments it is passed.  Note that
123           this returns a CODEREF, as currying does not yet happen. eg:
124           flip(sub { $_[0] ** $_[1] })->(2, 3) = 9.  In Haskell (ie this is
125           what it should really do):
126
127             flip           :: (a -> b -> c) -> b -> a -> c
128             flip f x y      = f y x
129
130       Until p f x
131           Keep on applying f to x until p(x) is true, and then return x at
132           that point. eg:
133
134             $x = Until { shift() % 10 == 0 } \&inc, 1; # 10
135
136           In Haskell:
137
138             until          :: (a -> Bool) -> (a -> a) -> a -> a
139             until p f x     = if p x then x else until p f (f x)
140
141       fst x:xs
142           Returns the first element in a tuple. eg:
143
144             $x = fst([1, 2]); # 1
145
146           In Haskell:
147
148             fst            :: (a,b) -> a
149             fst (x,_)       = x
150
151       snd x:y:xs
152           Returns the second element in a tuple. eg:
153
154             $x = snd([1, 2]); # 2
155
156           In Haskell:
157
158             snd            :: (a,b) -> a
159             snd (_,y)       = y
160
161       head xs
162           Returns the head (first element) of a list. eg:
163
164             $x = head([1..6]); # 1
165
166           In Haskell:
167
168             head             :: [a] -> a
169             head (x:_)        = x
170
171       Last xs
172           Returns the last element of a list. Note the capital L, to make it
173           distinct from the Perl 'last' command. eg:
174
175             $x = Last([1..6]); # 6
176
177           In Haskell:
178
179             last             :: [a] -> a
180             last [x]          = x
181             last (_:xs)       = last xs
182
183       tail xs
184           Returns a list minus the first element (head). eg:
185
186             $x = tail([1..6]); # [2, 3, 4, 5, 6]
187
188           In Haskell:
189
190             tail             :: [a] -> [a]
191             tail (_:xs)       = xs
192
193       init xs
194           Returns a list minus its last element. eg:
195
196             $x = init([1..6]); # [1, 2, 3, 4, 5]
197
198           In Haskell:
199
200             init             :: [a] -> [a]
201             init [x]          = []
202             init (x:xs)       = x : init xs
203
204       null xs
205           Returns whether or not the list is empty. eg:
206
207             $x = null([1, 2]); # False
208
209           In Haskell:
210
211             null             :: [a] -> Bool
212             null []           = True
213             null (_:_)        = False
214
215       Map f xs
216           Evaluates f for each element of the list xs and returns the list
217           composed of the results of each such evaluation. It is very similar
218           to the Perl command 'map', hence the capital M, but also copes with
219           infinite lists. eg:
220
221             $x = Map { double(shift) } [1..6]; # [2, 4, 6, 8, 10, 12]
222
223           In Haskell:
224
225             map              :: (a -> b) -> [a] -> [b]
226             map f xs          = [ f x | x <- xs ]
227
228       filter p xs
229           Returns the list of the elements in xs for which p(xs) returns
230           true. It is similar to the Perl command 'grep', but it also copes
231           with infinite lists. eg:
232
233             $x = filter(\&even, [1..6]); # [2, 4, 6]
234
235           In Haskell:
236
237             filter           :: (a -> Bool) -> [a] -> [a]
238             filter p xs       = [ x | x <- xs, p x ]
239
240       concat
241           Concatenates lists together into one list. eg:
242
243             concat([[1..3], [4..6]]); # [1, 2, 3, 4, 5, 6]
244
245           In Haskell:
246
247             concat           :: [[a]] -> [a]
248             concat            = foldr (++) []
249
250           TODO: Make sure this works with infinite lists!
251
252       Length
253           Returns the length of a list - only do this with finite lists! eg:
254
255             $x = Length([1..6]); # 6
256
257           In Haskell:
258
259             length           :: [a] -> Int
260             length            = foldl' (\n _ -> n + 1) 0
261
262           TODO Make sure this works!
263
264       foldl f z xs
265           Applies function f to the pairs (z, xs[0]), (f(z, xs[0], xs[1]),
266           (f(f(z, xs[0], xs[1])), xs[2]) and so on. ie it folds from the left
267           and returns the last value.  Note that foldl should not be done to
268           infinite lists. eg: the following returns the sum of 1..6:
269
270             $x = foldl { shift() + shift() } 0, [1..6]; # 21
271
272           In Haskell:
273
274             foldl            :: (a -> b -> a) -> a -> [b] -> a
275             foldl f z []      = z
276             foldl f z (x:xs)  = foldl f (f z x) xs
277
278       foldl1 f xs
279           This is a variant of foldl where the first value of xs is taken as
280           z. Applies function f to the pairs (xs[0], xs[1]), (f(xs[0], xs[1],
281           xs[2]), (f(f(xs[0], xs[1], xs[2])), xs[3]) and so on. ie it folds
282           from the left and returns the last value.  Note that foldl should
283           not be done to infinite lists. eg: the following returns the sum of
284           1..6:
285
286             $x = foldl1 { shift() + shift() } [1..6]; # 21
287
288           In Haskell:
289
290             foldl1           :: (a -> a -> a) -> [a] -> a
291             foldl1 f (x:xs)   = foldl f x xs
292
293       scanl f q xs
294           Returns a list of all the intermedia values that foldl would
295           compute.  ie returns the list z, f(z, xs[0]), f(f(z, xs[0]),
296           xs[1]), f(f(f(z, xs[0]), xs[1]), xs[2]) and so on. eg:
297
298             $x = scanl { shift() + shift() }, 0, [1..6]; # [0, 1, 3, 6, 10, 15, 21]
299
300           In Haskell:
301
302             scanl        :: (a -> b -> a) -> a -> [b] -> [a]
303             scanl f q xs  = q : (case xs of
304                                  []   -> []
305                                  x:xs -> scanl f (f q x) xs)
306
307       scanl1 f xs
308           This is a variant of scanl where the first value of xs is taken as
309           q. Returns a list of all the intermedia values that foldl would
310           compute.  ie returns the list f(xs[0], xs[1]), f(f(xs[0], xs[1]),
311           xs[2]), f(f(f(xs[0], xs[1]), xs[2]), xs[3]) and so on. eg:
312
313             $x = scanl1 { shift() + shift() } [1..6]; # [1, 3, 6, 10, 15, 21]
314
315           In Haskell:
316
317             scanl1           :: (a -> a -> a) -> [a] -> [a]
318             scanl1 f (x:xs)   = scanl f x xs
319
320       foldr f z xs
321           This is similar to foldl but is folding from the right instead of
322           the left.  Note that foldr should not be done to infinite lists.
323           eg: the following returns the sum of 1..6
324
325             $x = foldr { shift() + shift() } 0, [1..6] ; # 21
326
327           In Haskell:
328
329             foldr            :: (a -> b -> b) -> b -> [a] -> b
330             foldr f z []      = z
331             foldr f z (x:xs)  = f x (foldr f z xs)
332
333       foldr1 f xs
334           This is similar to foldr1 but is folding from the right instead of
335           the left. Note that foldr1 should not be done on infinite lists.
336           eg:
337
338             $x = foldr1 { shift() + shift() } [1..6]; # 21
339
340           In Haskell:
341
342             foldr1           :: (a -> a -> a) -> [a] -> a
343             foldr1 f [x]      = x
344             foldr1 f (x:xs)   = f x (foldr1 f xs)
345
346       scanr f z xs
347           This is similar to scanl but is scanning and folding from the right
348           instead of the left. Note that scanr should not be done on infinite
349           lists. eg:
350
351             $x = scanr { shift() + shift() } 0, [1..6];
352             # [0, 6, 11, 15, 18, 20, 21]
353
354           In Haskell:
355
356             scanr            :: (a -> b -> b) -> b -> [a] -> [b]
357             scanr f q0 []     = [q0]
358             scanr f q0 (x:xs) = f x q : qs
359                                 where qs@(q:_) = scanr f q0 xs
360
361       scanr1 f xs
362           This is similar to scanl1 but is scanning and folding from the
363           right instead of the left. Note that scanr1 should not be done on
364           infinite lists. eg:
365
366             $x = scanr1 { shift() + shift() } [1..6];
367             # [6, 11, 15, 18, 20, 21]
368
369           In Haskell:
370
371             scanr1           :: (a -> a -> a) -> [a] -> [a]
372             scanr1 f [x]      = [x]
373             scanr1 f (x:xs)   = f x q : qs
374                                 where qs@(q:_) = scanr1 f xs
375
376       iterate f x
377           This returns the infinite list (x, f(x), f(f(x)), f(f(f(x)))...)
378           and so on. eg:
379
380             $x = take(8, iterate { shift() * 2 } 1);
381             # [1, 2, 4, 8, 16, 32, 64, 128]
382
383           In Haskell:
384
385             iterate          :: (a -> a) -> a -> [a]
386             iterate f x       = x : iterate f (f x)
387
388       repeat x
389           This returns the infinite list where all elements are x. eg:
390
391             $x = take(4, repeat(42)); # [42, 42, 42, 42].
392
393           In Haskell:
394
395             repeat           :: a -> [a]
396             repeat x          = xs where xs = x:xs
397
398       replicate n x
399           Returns a list containing n times the element x. eg:
400
401             $x = replicate(5, 1); # [1, 1, 1, 1, 1]
402
403           In Haskell:
404
405             replicate        :: Int -> a -> [a]
406             replicate n x     = take n (repeat x)
407
408       take n xs
409           Returns a list containing the first n elements from the list xs.
410           eg:
411
412             $x = take(2, [1..6]); # [1, 2]
413
414           In Haskell:
415
416             take                :: Int -> [a] -> [a]
417             take 0 _             = []
418             take _ []            = []
419             take n (x:xs) | n>0  = x : take (n-1) xs
420             take _ _             = error "Prelude.take: negative argument"
421
422       drop n xs
423           Returns a list containing xs with the first n elements missing. eg:
424
425             $x = drop(2, [1..6]); # [3, 4, 5, 6]
426
427           In Haskell:
428
429             drop                :: Int -> [a] -> [a]
430             drop 0 xs            = xs
431             drop _ []            = []
432             drop n (_:xs) | n>0  = drop (n-1) xs
433             drop _ _             = error "Prelude.drop: negative argument"
434
435       splitAt n xs
436           Splits the list xs into two lists at element n. eg:
437
438             $x = splitAt(2, [1..6]);# [[1, 2], [3, 4, 5, 6]]
439
440           In Haskell:
441
442             splitAt               :: Int -> [a] -> ([a], [a])
443             splitAt 0 xs           = ([],xs)
444             splitAt _ []           = ([],[])
445             splitAt n (x:xs) | n>0 = (x:xs',xs'') where (xs',xs'') = splitAt (n-1) xs
446             splitAt _ _            = error "Prelude.splitAt: negative argument"
447
448       takeWhile p xs
449           Takes elements from xs while p(that element) is true. Returns the
450           list. eg:
451
452             $x = takeWhile { shift() <= 4 } [1..6]; # [1, 2, 3, 4]
453
454           In Haskell:
455
456             takeWhile           :: (a -> Bool) -> [a] -> [a]
457             takeWhile p []       = []
458             takeWhile p (x:xs)
459                      | p x       = x : takeWhile p xs
460                      | otherwise = []
461
462       dropWhile p xs
463           Drops elements from the head of xs while p(that element) is true.
464           Returns the list. eg:
465
466             $x = dropWhile { shift() <= 4 } [1..6]; # [5, 6]
467
468           In Haskell:
469
470             dropWhile           :: (a -> Bool) -> [a] -> [a]
471             dropWhile p []       = []
472             dropWhile p xs@(x:xs')
473                      | p x       = dropWhile p xs'
474                      | otherwise = xs
475
476       span p xs
477           Splits xs into two lists, the first containing the first few
478           elements for which p(that element) is true. eg:
479
480             $x = span { shift() <= 4 }, [1..6];
481             # [[1, 2, 3, 4], [5, 6]]
482
483           In Haskell:
484
485             span                :: (a -> Bool) -> [a] -> ([a],[a])
486             span p []            = ([],[])
487             span p xs@(x:xs')
488                      | p x       = (x:ys, zs)
489                      | otherwise = ([],xs)
490                                    where (ys,zs) = span p xs'
491
492       break p xs
493           Splits xs into two lists, the first containing the first few
494           elements for which p(that element) is false. eg:
495
496             $x = break { shift() >= 4 }, [1..6]; # [[1, 2, 3], [4, 5, 6]]
497
498           In Haskell:
499
500             break         :: (a -> Bool) -> [a] -> ([a],[a])
501             break p        = span (not . p)
502
503       lines s
504           Breaks the string s into multiple strings, split at line
505           boundaries. eg:
506
507             $x = lines("A\nB\nC"); # ['A', 'B', 'C']
508
509           In Haskell:
510
511             lines     :: String -> [String]
512             lines ""   = []
513             lines s    = let (l,s') = break ('\n'==) s
514                          in l : case s' of []      -> []
515                                            (_:s'') -> lines s''
516
517       words s
518           Breaks the string s into multiple strings, split at whitespace
519           boundaries. eg:
520
521             $x = words("hey how random"); # ['hey', 'how', 'random']
522
523           In Haskell:
524
525             words     :: String -> [String]
526             words s    = case dropWhile isSpace s of
527                               "" -> []
528                               s' -> w : words s''
529                                     where (w,s'') = break isSpace s'
530
531       unlines xs
532           Does the opposite of unlines, that is: joins multiple strings into
533           one, joined by newlines. eg:
534
535             $x = unlines(['A', 'B', 'C']); # "A\nB\nC";
536
537           In Haskell:
538
539             unlines   :: [String] -> String
540             unlines    = concatMap (\l -> l ++ "\n")
541
542           (note that strings in Perl are not lists of characters, so this
543           approach will not actually work...)
544
545       unwords ws
546           Does the opposite of unwords, that is: joins multiple strings into
547           one, joined by a space. eg:
548
549             $x = unwords(["hey","how","random"]); # 'hey how random'
550
551           In Haskell:
552
553             unwords   :: [String] -> String
554             unwords [] = []
555             unwords ws = foldr1 (\w s -> w ++ ' ':s) ws
556
557       Reverse xs
558           Returns a list containing the elements of xs in reverse order. Note
559           the capital R, so as not to clash with the Perl command 'reverse'.
560           You should not try to Reverse an infinite list.  eg:
561
562             $x = Reverse([1..6]); # [6, 5, 4, 3, 2, 1]
563
564           In Haskell:
565
566             reverse   :: [a] -> [a]
567             reverse    = foldl (flip (:)) []
568
569       And xs
570           Returns true if all the elements in xs are true. Returns false
571           otherwise. Note the capital A, so as not to clash with the Perl
572           command 'and'. You should not try to And an infinite list (unless
573           you expect it to fail, as it will short-circuit).  eg:
574
575             $x = And([1, 1, 1]); # 1
576
577           In Haskell:
578
579             and       :: [Bool] -> Bool
580             and        = foldr (&&) True
581
582       Or xs
583           Returns true if one of the elements in xs is true. Returns false
584           otherwise. Note the capital O, so as not to clash with the Perl
585           command 'or'. You may try to Or an infinite list as it will short-
586           circuit (unless you expect it to fail, that is). eg:
587
588             $x = Or([0, 0, 1]); # 1
589
590           In Haskell:
591
592             or        :: [Bool] -> Bool
593             or         = foldr (||) False
594
595       any p xs
596           Returns true if one of p(each element of xs) are true. Returns
597           false otherwise. You should not try to And an infinite list (unless
598           you expect it to fail, as it will short-circuit).  eg:
599
600             $x = any { even(shift) } [1, 2, 3]; # 1
601
602           In Haskell:
603
604             any       :: (a -> Bool) -> [a] -> Bool
605             any p      = or  . map p
606
607       all p xs
608           Returns true if all of the p(each element of xs) is true. Returns
609           false otherwise. You may try to Or an infinite list as it will
610           short-circuit (unless you expect it to fail, that is). eg:
611
612             $x = all { odd(shift) } [1, 1, 3]; # 1
613
614           In Haskell:
615
616             all  :: (a -> Bool) -> [a] -> Bool
617             all p      = and . map p
618
619       elem x xs
620           Returns true is x is present in xs.  You probably should not do
621           this with infinite lists.  Note that this assumes x and xs are
622           numbers.  eg:
623
624             $x = elem(2, [1, 2, 3]); # 1
625
626           In Haskell:
627
628             elem             :: Eq a => a -> [a] -> Bool
629             elem              = any . (==)
630
631       notElem x xs
632           Returns true if x is not present in x. You should not do this with
633           infinite lists. Note that this assumes that x and xs are numbers.
634           eg:
635
636             $x = notElem(2, [1, 1, 3]); # 1
637
638           In Haskell:
639
640             notElem          :: Eq a => a -> [a] -> Bool
641             notElem           = all . (/=)
642
643       lookup key xys
644           This returns the value of the key in xys, where xys is a list of
645           key, value pairs. It returns undef if the key was not found. You
646           should not do this with infinite lists. Note that this assumes that
647           the keys are strings. eg:
648
649             $x = lookup(3, [1..6]); # 4
650
651           In Haskell:
652
653             lookup           :: Eq a => a -> [(a,b)] -> Maybe b
654             lookup k []       = Nothing
655             lookup k ((x,y):xys)
656                   | k==x      = Just y
657                   | otherwise = lookup k xys
658
659           TODO: Make sure this works with infinite lists
660
661       minimum xs
662           Returns the minimum value in xs.  You should not do this with a
663           infinite list.  eg:
664
665             $x = minimum([1..6]); # 1
666
667           In Haskell:
668
669             minimum          :: Ord a => [a] -> a
670             minimum           = foldl1 min
671
672       maximum xs
673           Returns the maximum value in xs.  You should not do this with an
674           infinite list.  eg: maximum([1..6]) = 6. In Haskell:
675
676               maximum          :: Ord a => [a] -> a
677               maximum           = foldl1 max
678
679       sum xs
680           Returns the sum of the elements of xs.  You should not do this with
681           an infinite list.  eg: sum([1..6]) = 21. In Haskell:
682
683               sum          :: Num a => [a] -> a
684               sum           = foldl' (+) 0
685
686       product xs
687           Returns the products of the elements of xs.  You should not do this
688           with an infinite list.  eg: product([1..6]) = 720. In Haskell:
689
690               product      :: Num a => [a] -> a
691               product       = foldl' (*) 1
692
693       zip as bs
694           Zips together two lists into one list. Should not be done with
695           infinite lists.  eg: zip([1..6], [7..12]) = [1, 7, 2, 8, 3, 9, 4,
696           10, 5, 11, 6, 12].  In Haskell:
697
698               zip              :: [a] -> [b] -> [(a,b)]
699               zip               = zipWith  (\a b -> (a,b))
700
701               zipWith                  :: (a->b->c) -> [a]->[b]->[c]
702               zipWith z (a:as) (b:bs)   = z a b : zipWith z as bs
703               zipWith _ _      _        = []
704
705       zip3 as bs cs
706           Zips together three lists into one. Should not be done with
707           infinite lists.  eg: zip3([1..2], [3..4], [5..6]) = [1, 3, 5, 2, 4,
708           6].  In Haskell:
709
710               zip3             :: [a] -> [b] -> [c] -> [(a,b,c)]
711               zip3              = zipWith3 (\a b c -> (a,b,c))
712
713               zipWith3                 :: (a->b->c->d) -> [a]->[b]->[c]->[d]
714               zipWith3 z (a:as) (b:bs) (c:cs)
715                                         = z a b c : zipWith3 z as bs cs
716               zipWith3 _ _ _ _          = []
717
718       unzip abs
719           Unzips one list into two. Should not be done with infinite lists.
720           eg: unzip([1,7,2,8,3,9,4,10,5,11,6,12]) = ([1, 2, 3, 4, 5, 6], [7,
721           8, 9, 10, 11, 12]).
722
723               unzip    :: [(a,b)] -> ([a],[b])
724               unzip     = foldr (\(a,b) ~(as,bs) -> (a:as, b:bs)) ([], [])
725
726       unzip abcs
727           Unzips one list into three. Should not be done with infinite lists.
728           eg: unzip3([1,3,5,2,4,6]) = ([1, 2], [3, 4], [5, 6]).  In Haskell:
729
730               unzip3   :: [(a,b,c)] -> ([a],[b],[c])
731               unzip3    = foldr (\(a,b,c) ~(as,bs,cs) -> (a:as,b:bs,c:cs))
732                                 ([],[],[])
733
734       integers
735           A useful function that returns an infinite list containing all the
736           integers. eg: integers = (1, 2, 3, 4, 5, ...).
737
738       factors x
739           A useful function that returns the factors of x.  eg: factors(100)
740           = [1, 2, 4, 5, 10, 20, 25, 50, 100].  In Haskell:
741
742               factors x = [n | n <- [1..x], x `mod` n == 0]
743
744       prime x
745           A useful function that returns, rather unefficiently, if x is a
746           prime number or not. It is rather useful while used as a filter,
747           eg: take(10, filter("prime", integers)) = [2, 3, 5, 7, 11, 13, 17,
748           19, 23, 29].  In Haskell:
749
750               primes = [n | n <- [2..], length (factors n) == 2]
751

AUTHOR

753       Leon Brocard <acme@astray.com>
754
756       Copyright (C) 1999-2008, Leon Brocard
757

LICENSE

759       This module is free software; you can redistribute it or modify it
760       under the same terms as Perl itself.
761
762
763
764perl v5.34.0                      2022-01-21                     Functional(3)
Impressum