This document compares and contrasts the programming languages Perl and Haskell. It discusses their differences in terms of being dynamic vs static, imperative vs functional, and weakly vs strongly typed. It provides examples of how similar tasks like mapping, doubling values, and finding lengths can be accomplished in both languages. It also explores some of the challenges that arise from Perl's scalar/list context and Haskell's use of monads and strong static types. Overall, the document examines the different philosophies behind Perl and Haskell while also showing how influences have flowed between the communities over time.
Some techniques from the heady world of Functional Programming implemented in idiomatic Perl using various techniques: closures, iterators, Devel::Declare, and some distilled evil. New version now with monads! (As presented at http://conferences.yapceurope.org/lpw2008/ )
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
All new material, this time about one of the fundamental functional datastructures, the Linked List, and the overview of an implementation in Moosey Perl.
This covers some of the same material as https://github.com/osfameron/pure-fp-book but perhaps with more explanation (and covering much less material - it was only a 20 minute talk)
Slides from my PyCon 2011 talk, "Exhibition of Atrocity," a confessional of my sins against the Python programming language.
Abstract: http://us.pycon.org/2011/schedule/presentations/138/
Video: http://www.pycon.tv/#/video/49
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
As a result of an engine rewrite with focus on more efficient data structures, PHP 7 offers much improved performance and memory usage. This session describes important aspects of the new implementation and how it compares to PHP 5. A particular focus will be on the representation of values, arrays and objects.
Some techniques from the heady world of Functional Programming implemented in idiomatic Perl using various techniques: closures, iterators, Devel::Declare, and some distilled evil. New version now with monads! (As presented at http://conferences.yapceurope.org/lpw2008/ )
Functional Pe(a)rls - the Purely Functional Datastructures editionosfameron
All new material, this time about one of the fundamental functional datastructures, the Linked List, and the overview of an implementation in Moosey Perl.
This covers some of the same material as https://github.com/osfameron/pure-fp-book but perhaps with more explanation (and covering much less material - it was only a 20 minute talk)
Slides from my PyCon 2011 talk, "Exhibition of Atrocity," a confessional of my sins against the Python programming language.
Abstract: http://us.pycon.org/2011/schedule/presentations/138/
Video: http://www.pycon.tv/#/video/49
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
One of the main selling points of PHP 7 is greatly improved performance, with many real-world applications now running twice as fast… But where do these improvements come from?
At the core of PHP 7 lies an engine rewrite with focus on improving memory usage and performance. This talk provides an overview of the most significant changes, briefly covering everything from data structure changes, over enhancements in the executor, to the new compiler implementation.
As a result of an engine rewrite with focus on more efficient data structures, PHP 7 offers much improved performance and memory usage. This session describes important aspects of the new implementation and how it compares to PHP 5. A particular focus will be on the representation of values, arrays and objects.
An Elephant of a Different Colour: HackVic Metcalfe
Slides from my GTA-PHP Meetup talk about Hack which is the Facebook version of the PHP programming language which runs under their HHVM runtime environment for PHP. The focus of my talk was the language improvements that the Facebook team has added to PHP.
There's a lot of information in the presenter's notes, so if you're interested in Hack scroll down to see the extras.
There are a lot of operators in Perl 6, so many that it can be called an OOL: operator oriented language. Here I describe most of them from the angle of contexts, which Perl 6 has also much more than Perl 5.
This contains all the slides used in Silicon Valley Code Camp presentation on Sunday Oct 4, 10:45 session on "Amazing new features in JavaScript". At the end ut also includes the last year presentation covering ES 5
Conheça um pouco mais sobre Perl 6, uma linguagem de programação moderna, poderosa e robusta que permitirá que você escreva código de forma ágil e eficiente.
An Elephant of a Different Colour: HackVic Metcalfe
Slides from my GTA-PHP Meetup talk about Hack which is the Facebook version of the PHP programming language which runs under their HHVM runtime environment for PHP. The focus of my talk was the language improvements that the Facebook team has added to PHP.
There's a lot of information in the presenter's notes, so if you're interested in Hack scroll down to see the extras.
There are a lot of operators in Perl 6, so many that it can be called an OOL: operator oriented language. Here I describe most of them from the angle of contexts, which Perl 6 has also much more than Perl 5.
This contains all the slides used in Silicon Valley Code Camp presentation on Sunday Oct 4, 10:45 session on "Amazing new features in JavaScript". At the end ut also includes the last year presentation covering ES 5
Conheça um pouco mais sobre Perl 6, uma linguagem de programação moderna, poderosa e robusta que permitirá que você escreva código de forma ágil e eficiente.
Python's "batteries included" philosophy means that it comes with an astonishing amount of great stuff. On top of that, there's a vibrant world of third-party libraries that help make Python even more wonderful. We'll go on a breezy, example-filled tour through some of my favorites, from treasures in the standard library to great third-party packages that I don't think I could live without, and we'll touch on some of the fuzzier aspects of the Python culture that make it such a joy to be part of.
A Recovering Java Developer Learns to GoMatt Stine
As presented at OSCON 2014.
The Go programming language has emerged as a favorite tool of DevOps and cloud practitioners alike. In many ways, Go is more famous for what it doesn’t include than what it does, and co-author Rob Pike has said that Go represents a “less is more” approach to language design.
The Cloud Foundry engineering teams have steadily increased their use of Go for building components, starting with the Router, and progressing through Loggregator, the CLI, and more recently the Health Manager. As a “recovering-Java-developer-turned-DevOps-junkie” focused on helping our customers and community succeed with Cloud Foundry, it became very clear to me that I needed to add Go to my knowledge portfolio.
This talk will introduce Go and its distinctives to Java developers looking to add Go to their toolkits. We’ll cover Go vs. Java in terms of:
* type systems
* modularity
* programming idioms
* object-oriented constructs
* concurrency
FITC events. For digital creators.
Save 10% off ANY FITC event with discount code 'slideshare'
See our upcoming events at www.fitc.ca
An Intro To ES6
with Grant Skinner
OVERVIEW
ECMAScript 6 is the approved and published standard for the next version of JavaScript. It offers new syntax and language features that provide new ways of tackling coding problems, and increase your productivity.
This session will introduce ES6 and delve into many of the new features of the language. It will also cover real-world use, including transpilers, runtimes, and browser support.
OBJECTIVE
Create confidence in evaluating and getting started using ES6.
TARGET AUDIENCE
JavaScript developers.
ASSUMED AUDIENCE KNOWLEDGE
JavaScript.
FOUR THINGS AUDIENCE MEMBERS WILL LEARN
Status of ES6
How to get started with ES6
ES6 feature overview
Practical considerations for adopting ES6
Ever wondered how to write a tile-matching game (like Candy Crush and the earlier Bejeweled)? Traditionally game developers would write a game - the graphics, state, and user interaction - in an imperative style, but recently the functional approach is getting more popular.
Hakim Cassimally (BBC, Manchester LambdaLounge) has been exploring the process of developing a tile-matching game in Clojure. He'll present present some of the basics of modelling the game grid, and playing a basic event loop, introducing some important concepts in functional programming and simple game development.
This is a beginner-friendly talk, originally given at def_shef 43 in Sheffield UK, Tuesday 9th January 2018.
Data structures for Text Editors: Hakim Cassimally @osfameron
Lambda Lounge Manchester, Mon 16th Jan 2017
There are some notes in the tab below on SlideShare. Alternatively, you can download a PDF with full notes from https://www.dropbox.com/s/gxi2zbb861f82vw/text-editors-with-notes.pdf?dl=0
I don't normally draw slides, but this time I started to get grumpy about drawing boxes in Keynote and decided it would actually be easier to use pen and paper. I'm not sure if the result looks good, but it kept me amused and was mostly fun (taking photos of the resulting thing was a bit of a faff.)
LambdaLounge is a meetup for functional programmers, and this talk has a focus on immutable data-structures. There are few code examples (it turns out that one (dis?)advantage of drawing slides is that you don't really feel like writing out large chunks of source code) but what little there is is in Clojure.
* How is the Internet of Things like knitting?
* Is the Perl community bigger on the inside?
* And is surviving the apocalypse just a question of being in the right universe at the right time?
Let's travel 100 years into the future to answer all these questions and more.
Global Civic Hacking 101 (lightning talk)osfameron
My Lightning Talk from YAPC::EU::2014 Sofia. An introduction to civic hacking around the world, with some examples from the UK, Latin America and Taiwan.
What is civic hacking, and what does it have to do with fixing potholes? My talk from YAPC::EU::2014 in Sofia.
https://www.youtube.com/watch?v=pUp1mQx61No
A short talk on what makes Functional Programming - and especially Haskell - different.
We'll take a quick overview of Haskell's features and coding style, and then work through a short but complete example of using it for a Real World problem.
http://lanyrd.com/2011/geekup-liverpool-may/sdykh/
Oyster: an incubator for perls in the cloudosfameron
My proposal for northwestengland.pm's Hackday. Oyster will be an opensource set of tools and modules to enable easy provisioning and deployment of Perl web-apps to the cloud.
Oyster was selected as the main application for the Hackday on 20th December. During the day we'll also be working on Iain's "Hackday in a Box" application (which will be the first test application for Oyster!); triaging Perl bugs; and adding features to last year's project Ironman. Why Aim So Low indeed!
Unix has always had a philosophy of composable tools, where one tool outputs to the next in a pipeline.
But the technique of piping a *textual* stream of data, and having to extract data out of it is looking a bit long in the tooth. Microsoft (not historically an innovator in its shell environment :-) has stolen a march with its Powershell.
Can we do better in Perl? With composable streams of objects? Written in a modern OO framework (Moose)?
You bet we can!
This talk was given at the London Perl Workshop 2009, http://conferences.yapceurope.org/lpw2009/talk/2456
People like to claim Perl is line noise, with its sigils and regular expressions. But a lot of the features that make it possible to write, yes, truly awful, unreadable Perl, also let you write clean, maintainable code too.
* those $%&* sigils!
* there\'s More Than One Way To Do It
* strings and data structures
* map, grep, first class functions
* metaprogramming and the CPAN
* modern Object Oriented programming with Moose
Navigating the Metaverse: A Journey into Virtual Evolution"Donna Lenk
Join us for an exploration of the Metaverse's evolution, where innovation meets imagination. Discover new dimensions of virtual events, engage with thought-provoking discussions, and witness the transformative power of digital realms."
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...Juraj Vysvader
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I didn't get rich from it but it did have 63K downloads (powered possible tens of thousands of websites).
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisGlobus
JASMIN is the UK’s high-performance data analysis platform for environmental science, operated by STFC on behalf of the UK Natural Environment Research Council (NERC). In addition to its role in hosting the CEDA Archive (NERC’s long-term repository for climate, atmospheric science & Earth observation data in the UK), JASMIN provides a collaborative platform to a community of around 2,000 scientists in the UK and beyond, providing nearly 400 environmental science projects with working space, compute resources and tools to facilitate their work. High-performance data transfer into and out of JASMIN has always been a key feature, with many scientists bringing model outputs from supercomputers elsewhere in the UK, to analyse against observational or other model data in the CEDA Archive. A growing number of JASMIN users are now realising the benefits of using the Globus service to provide reliable and efficient data movement and other tasks in this and other contexts. Further use cases involve long-distance (intercontinental) transfers to and from JASMIN, and collecting results from a mobile atmospheric radar system, pushing data to JASMIN via a lightweight Globus deployment. We provide details of how Globus fits into our current infrastructure, our experience of the recent migration to GCSv5.4, and of our interest in developing use of the wider ecosystem of Globus services for the benefit of our user community.
Zoom is a comprehensive platform designed to connect individuals and teams efficiently. With its user-friendly interface and powerful features, Zoom has become a go-to solution for virtual communication and collaboration. It offers a range of tools, including virtual meetings, team chat, VoIP phone systems, online whiteboards, and AI companions, to streamline workflows and enhance productivity.
Do you want Software for your Business? Visit Deuglo
Deuglo has top Software Developers in India. They are experts in software development and help design and create custom Software solutions.
Deuglo follows seven steps methods for delivering their services to their customers. They called it the Software development life cycle process (SDLC).
Requirement — Collecting the Requirements is the first Phase in the SSLC process.
Feasibility Study — after completing the requirement process they move to the design phase.
Design — in this phase, they start designing the software.
Coding — when designing is completed, the developers start coding for the software.
Testing — in this phase when the coding of the software is done the testing team will start testing.
Installation — after completion of testing, the application opens to the live server and launches!
Maintenance — after completing the software development, customers start using the software.
Globus Connect Server Deep Dive - GlobusWorld 2024Globus
We explore the Globus Connect Server (GCS) architecture and experiment with advanced configuration options and use cases. This content is targeted at system administrators who are familiar with GCS and currently operate—or are planning to operate—broader deployments at their institution.
We describe the deployment and use of Globus Compute for remote computation. This content is aimed at researchers who wish to compute on remote resources using a unified programming interface, as well as system administrators who will deploy and operate Globus Compute services on their research computing infrastructure.
In the ever-evolving landscape of technology, enterprise software development is undergoing a significant transformation. Traditional coding methods are being challenged by innovative no-code solutions, which promise to streamline and democratize the software development process.
This shift is particularly impactful for enterprises, which require robust, scalable, and efficient software to manage their operations. In this article, we will explore the various facets of enterprise software development with no-code solutions, examining their benefits, challenges, and the future potential they hold.
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Globus
The Earth System Grid Federation (ESGF) is a global network of data servers that archives and distributes the planet’s largest collection of Earth system model output for thousands of climate and environmental scientists worldwide. Many of these petabyte-scale data archives are located in proximity to large high-performance computing (HPC) or cloud computing resources, but the primary workflow for data users consists of transferring data, and applying computations on a different system. As a part of the ESGF 2.0 US project (funded by the United States Department of Energy Office of Science), we developed pre-defined data workflows, which can be run on-demand, capable of applying many data reduction and data analysis to the large ESGF data archives, transferring only the resultant analysis (ex. visualizations, smaller data files). In this talk, we will showcase a few of these workflows, highlighting how Globus Flows can be used for petabyte-scale climate analysis.
First Steps with Globus Compute Multi-User EndpointsGlobus
In this presentation we will share our experiences around getting started with the Globus Compute multi-user endpoint. Working with the Pharmacology group at the University of Auckland, we have previously written an application using Globus Compute that can offload computationally expensive steps in the researcher's workflows, which they wish to manage from their familiar Windows environments, onto the NeSI (New Zealand eScience Infrastructure) cluster. Some of the challenges we have encountered were that each researcher had to set up and manage their own single-user globus compute endpoint and that the workloads had varying resource requirements (CPUs, memory and wall time) between different runs. We hope that the multi-user endpoint will help to address these challenges and share an update on our progress here.
Utilocate offers a comprehensive solution for locate ticket management by automating and streamlining the entire process. By integrating with Geospatial Information Systems (GIS), it provides accurate mapping and visualization of utility locations, enhancing decision-making and reducing the risk of errors. The system's advanced data analytics tools help identify trends, predict potential issues, and optimize resource allocation, making the locate ticket management process smarter and more efficient. Additionally, automated ticket management ensures consistency and reduces human error, while real-time notifications keep all relevant personnel informed and ready to respond promptly.
The system's ability to streamline workflows and automate ticket routing significantly reduces the time taken to process each ticket, making the process faster and more efficient. Mobile access allows field technicians to update ticket information on the go, ensuring that the latest information is always available and accelerating the locate process. Overall, Utilocate not only enhances the efficiency and accuracy of locate ticket management but also improves safety by minimizing the risk of utility damage through precise and timely locates.
Introducing Crescat - Event Management Software for Venues, Festivals and Eve...Crescat
Crescat is industry-trusted event management software, built by event professionals for event professionals. Founded in 2017, we have three key products tailored for the live event industry.
Crescat Event for concert promoters and event agencies. Crescat Venue for music venues, conference centers, wedding venues, concert halls and more. And Crescat Festival for festivals, conferences and complex events.
With a wide range of popular features such as event scheduling, shift management, volunteer and crew coordination, artist booking and much more, Crescat is designed for customisation and ease-of-use.
Over 125,000 events have been planned in Crescat and with hundreds of customers of all shapes and sizes, from boutique event agencies through to international concert promoters, Crescat is rigged for success. What's more, we highly value feedback from our users and we are constantly improving our software with updates, new features and improvements.
If you plan events, run a venue or produce festivals and you're looking for ways to make your life easier, then we have a solution for you. Try our software for free or schedule a no-obligation demo with one of our product specialists today at crescat.io
GraphSummit Paris - The art of the possible with Graph TechnologyNeo4j
Sudhir Hasbe, Chief Product Officer, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
Graspan: A Big Data System for Big Code AnalysisAftab Hussain
We built a disk-based parallel graph system, Graspan, that uses a novel edge-pair centric computation model to compute dynamic transitive closures on very large program graphs.
We implement context-sensitive pointer/alias and dataflow analyses on Graspan. An evaluation of these analyses on large codebases such as Linux shows that their Graspan implementations scale to millions of lines of code and are much simpler than their original implementations.
These analyses were used to augment the existing checkers; these augmented checkers found 132 new NULL pointer bugs and 1308 unnecessary NULL tests in Linux 4.4.0-rc5, PostgreSQL 8.3.9, and Apache httpd 2.2.18.
- Accepted in ASPLOS ‘17, Xi’an, China.
- Featured in the tutorial, Systemized Program Analyses: A Big Data Perspective on Static Analysis Scalability, ASPLOS ‘17.
- Invited for presentation at SoCal PLS ‘16.
- Invited for poster presentation at PLDI SRC ‘16.
OpenMetadata Community Meeting - 5th June 2024OpenMetadata
The OpenMetadata Community Meeting was held on June 5th, 2024. In this meeting, we discussed about the data quality capabilities that are integrated with the Incident Manager, providing a complete solution to handle your data observability needs. Watch the end-to-end demo of the data quality features.
* How to run your own data quality framework
* What is the performance impact of running data quality frameworks
* How to run the test cases in your own ETL pipelines
* How the Incident Manager is integrated
* Get notified with alerts when test cases fail
Watch the meeting recording here - https://www.youtube.com/watch?v=UbNOje0kf6E
1. Is Haskell an
Acceptable Perl?
@osfameron
LambdaLounge MadLab 18 April 2016
https://github.com/osfameron/haskell-perl
2. Overview
Perl:
https://www.perl.org/
Perl 5 is a highly
capable, feature-rich
programming language
with over 27 years of
development
Haskell:
https://www.haskell.org/
An advanced purely-
functional programming
language
An open source community
effort for over 20 years
7. “Around 1993 I
started reading
books about Lisp,
and I discovered
something important:
Perl is much more
like Lisp than it is
like C.”
8. What Makes Lisp
Different?
“…describes seven
features of Lisp.
Perl shares six of
these features; C
shares none of them.
These are big,
important features,
features like first-
class functions,
dynamic access to the
symbol table, and
automatic storage
management.”
-- mjd
48. Tails
map __&tail, @l
=> ([2,3], [4,3,2,1])
sub tail ($head, @tail) {
@tail
}
{
no experimental 'signatures';
sub _ ($) { shift->($_) }
sub __ ($) { [shift->(@$_)] }
}
map tail l
=> [[2,3], [4,3,2,1]]
49. A thought...
Scalar/list context
Sigils ($, @, %)
implicit $_
Optional parameters
References and
dereferencing
Automatic type coercions
Subroutine prototypes
Type system
53. To be fair...
Perl:
• Larry Wall: linguist,
missionary
• + jobbing programmers
• pragmatic
• magpie-like
Haskell:
• Decades of Comp Sci
professors and PhD
students
• purity
• experimentation
54. Why are we* so terrified of types?
en2it :: M.Map [Char] [Char]
en2it = M.fromList [
("hello","ciao"),
("goodbye","ciao"),
("pasta","pasta") ]
translate :: (Monad m, Ord k) => M.Map k a -> k -> m a
translate db k =
let v = M.lookup k db
in case v of
Nothing -> fail "No translation"
Just v' -> return v'
55. Why are we* so terrified of types?
en2it :: M.Map [Char] [Char]
en2it = M.fromList [
("hello","ciao"),
("goodbye","ciao"),
("pasta","pasta") ]
translate :: (Monad m, Ord k) => M.Map k a -> k -> m a
translate db k =
let v = M.lookup k db
in case v of
Nothing -> fail "No translation"
Just v' -> return v'
56. Why are we* so terrified of types?
“Programming in ML is very pleasant. More than
almost any other language I know, you can just
write down the definitions of the functions as
they come into your head. You don't need to bother
with declarations; everything is just figured out
for you automatically.
And you do get a lot of type errors, both actual
failures and also places where the type emitted by
the compiler is not what you thought it should be.
But unlike in C or Pascal, every one of those
errors indicates a real, serious problem in your
program, not merely something you have to groan
over and try to work around the compiler's
stupidity yet again.”
-- mjd http://perl.plover.com/classes/typing/notes.html
57. Why are we* so terrified of types?
[4, 8, 15, 16, 23, 42] :: [Int]
59. Type terror: undefined values
my %en2it = (
hello => “ciao”,
goodbye => “ciao”,
pasta => “pasta”
);
my @l = map $en2it{$_},
(“hello", “monad", “pasta”);
my @c = grep defined, @l;
# (“ciao”, “pasta”)
60. Type terror: undefined values
-- data Maybe a = Just a | Nothing
l = map (flip Map.lookup h)
[“hello", “monad", “pasta”]
-- [Just “ciao”, Nothing, Just “pasta”]
c = catMaybes l
-- [“ciao”, “pasta”]
61. Type terror: signal values
[1, undef, 2, “X”, 3, -5]
# positive number: record
# undef: no record found
# “string”: processing instruction
# negative number: record flagged for
deletion
62. Type terror: signal values
records :: [Maybe Record]
records = [
Just Record (Left 1),
Nothing,
Just Record (Left 2),
Just Instruction “X”
Just Record (Left 2),
Just Record (Right 5)]
data Record =
Record (Either Int Int) | Instruction String
63. Type terror: but! but! but!
serialization (show)
objects of a particular class (typeclasses)
GADTs
existential types
dynamic introspection
...
65. april.txt
There is shadow under this red rock,
(Come in under the shadow of this red rock),
And I will show you something different from either
Your shadow at morning striding behind you
Or your shadow at evening rising to meet you;
I will show you fear in a handful of dust.
66. Grep for a string
$ perl -ne ‘print if /shadow/’ < april.txt
???
67. Grep for a string
$ perl -ne ‘print if /shadow/’ < april.txt
notaoneliner.hs:
import Data.List
main = interact (
unlines .
(filter (a -> "shadow" `isInfixOf` a))
. lines )
$ runghc notaoneliner.hs < april.txt
68. april.txt | grep shadow
There is shadow under this red rock,
(Come in under the shadow of this red rock),
Your shadow at morning striding behind you
Or your shadow at evening rising to meet you;
69. Grep for a string
$ perl -ne ‘print if /shadow/’ < april.txt
hask.bash:
if which ghc > /dev/null
then
function h { ghc -e "interact ($*)" Ust.hs ; }
function hl { h "bylines ($*)" ; }
function hw { h "bywords ($*)" ; }
fi
$ hl ‘filter (regexBool “shadow”)’ < april.txt
70. Ust.hs
https://wiki.haskell.org/Simple_Unix_tools
https://ulissesaraujo.wordpress.com/tag/command/
{-# LANGUAGE NoMonomorphismRestriction #-}
module Ust(
bylines, bywords, showln, regexBool, uniq, rpt, take', drop',
head', tail', tail10, tac, rev, rev_w, wc_c, wc_l, wc_w, space,
unspace, remove, upper, clean, clean', clean'', blank, join, tr,
tr_d, grep, grep_v, cksum
) where
import Control.Monad.Instances; import Data.List; import Data.Char;
import Data.Maybe; import Text.Printf; import System.Environment;
import Text.Regex.Posix
-- First, three helpers
bylines f = (unlines . f . lines)
bywords f = (unwords . f . words)
showln = (++ "n") . show
-- simple boolean regex matching
regexBool r l = l =~ r :: Bool
...
72. april.txt | upper
THERE IS SHADOW UNDER THIS RED ROCK,
(COME IN UNDER THE SHADOW OF THIS RED ROCK),
AND I WILL SHOW YOU SOMETHING DIFFERENT FROM EITHER
YOUR SHADOW AT MORNING STRIDING BEHIND YOU
OR YOUR SHADOW AT EVENING RISING TO MEET YOU;
I WILL SHOW YOU FEAR IN A HANDFUL OF DUST.
74. april.txt | sort
(Come in under the shadow of this red rock),
And I will show you something different from either
I will show you fear in a handful of dust.
Or your shadow at evening rising to meet you;
There is shadow under this red rock,
Your shadow at morning striding behind you
76. april.txt | sort-words
(Come And I I Or There Your a at at behind different
dust. either evening fear from handful in in is meet
morning of of red red rising rock), rock, shadow shadow
shadow shadow show show something striding the this
this to under under will will you you you you; your
79. Modelling TV programmes
Brand:
“Have I
Got News
For You?”
Series:
“3”
Episode:
“1” /
HIGNFY123
Brand:
“Have I
Got OLD
News For
You?”
Series:
“1”
Episode:
“5” /
HIGNFY123
80. Data modelling
package Programme;
use Moo;
use Types::Standard
qw/ Maybe Str /;
has id => ( is => 'ro',
isa => Maybe[Str] );
has id2 => ( is => 'ro',
isa => Maybe[Str] );
package Brand;
use Moo;
extends 'Programme';
# ditto Series, Episode...
type PrimaryId = Maybe String
type AlternateId = Maybe String
data Prog = Prog
ProgType
PrimaryId AlternateId
deriving (Eq, Ord, Show)
data ProgType =
Brand |
Series |
Episode
deriving (Eq, Ord, Show)
81. The “Database”
package Database;
use Moo;
use Types::Standard
qw/ArrayRef HashRef InstanceOf/;
has list => (
is => 'ro',
isa => ArrayRef[InstanceOf["Programme"]],
...
);
has graph => (
is => 'ro',
isa => HashRef[InstanceOf["Programme"]],
...
);
data Database = Database {
list :: [Prog],
graph :: M.Map Prog Prog
}
82. Get Hierarchy
use experimental ‘signatures’;
sub getHierarchy($self, $prog) {
if (my $parent = $self->lookup($prog->id)) {
return ($prog, $self->getHierarchy($parent))
}
else { return $prog }
}
getHierarchy :: Database -> Prog -> [Prog]
getHierarchy db p =
let l = M.lookup p (graph db)
in case l of
Nothing -> [p]
Just (parent) -> p : (getHierarchy db parent)
83. Get Hierarchy
use experimental ‘signatures’;
use MooX::HandlesVia;
has graph => (
is => 'ro',
isa => HashRef[InstanceOf["Programme"]],
handles_via => 'Hash',
handles => { lookup => ‘get’ }
);
sub getHierarchy($self, $prog) {
if (my $parent = $self->lookup($prog->id)) {
return ($prog, $self->getHierarchy($parent))
}
else { return $prog }
}
84. Search for a programme
sub search ($self, $prog1) {
my sub match ($prog2) {
return unless ref $prog1 eq ref $prog2;
return unless $prog1->id or $prog1->id2;
return unless $prog2->id or $prog2->id2;
return unless $prog1->id or $prog2->id2;
return unless $prog1->id2 or $prog2->id;
return if $prog1->id and $prog2->id and $prog1->id ne $prog2->id;
return if $prog1->id2 and $prog2->id2 and $prog1->id2 ne $prog2->id2;
return 1;
}
return $self->filter(&match);
}
85. Search for a programme
use experimental 'lexical_subs';
has list => (
is => 'ro',
isa => ArrayRef[InstanceOf["Programme"]],
handles_via => 'Array',
handles => { filter => 'grep'}
);
86. Search for a programme
search db p =
filter (match p) (list db)
where
match (Prog t1 _ _) (Prog t2 _ _) | t1 /= t2 = False
match (Prog _ Nothing Nothing) _ = False
match _ (Prog _ Nothing Nothing) = False
match (Prog _ Nothing _) (Prog _ _ Nothing) = False
match (Prog _ _ Nothing) (Prog _ Nothing _) = False
match (Prog _ (Just p1) _) (Prog _ (Just p2) _) | p1 /= p2 = False
match (Prog _ _ (Just a1)) (Prog _ _ (Just a2)) | a1 /= a2 = False
match _ _ = True