Created
September 3, 2014 12:55
-
-
Save pqr/53accffe9d8ed336908a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* php скрипт в функциональном стиле (калька с Haskell) для статьи http://pqr7.wordpress.com/2014/09/03/haskell-vs-php/ */ | |
ini_set('xdebug.max_nesting_level', 200000); | |
function parse($text) { | |
return splitPerBlocks(getLines($text)); | |
} | |
function getLines($text) { | |
return array_map('trim', explode("\n", $text)); | |
} | |
function splitPerBlocks(array $lines) { | |
return splitPerBlocksRecursiveFold([], $lines); | |
} | |
function splitPerBlocksRecursiveFold(array $blocks, array $lines) { | |
if (count($lines) < 20) { | |
return $blocks; | |
} | |
$linesWithoutHeaderAndFlag = dropFlagLine(dropHeaderLine($lines)); | |
if (count($linesWithoutHeaderAndFlag) >= 20) { | |
$first20Lines = array_slice($linesWithoutHeaderAndFlag, 0, 20); | |
$otherLines = array_slice($linesWithoutHeaderAndFlag, 20); | |
$newFoundBlocks = $blocks; | |
$newFoundBlocks[] = $first20Lines; | |
return splitPerBlocksRecursiveFold($newFoundBlocks, $otherLines); | |
} | |
return $blocks; | |
} | |
function dropHeaderLine(array $lines) { | |
if (strpos(reset($lines), "Container No.") !== false) { | |
return array_slice($lines, 1); | |
} | |
return $lines; | |
} | |
function dropFlagLine(array $lines) | |
{ | |
if (count($lines) <= 20) { | |
return $lines; | |
} | |
if (strpos($lines[20], "Flag:") !== false) { | |
return array_merge(array_slice($lines, 0, 20), array_slice($lines, 21)); | |
} | |
return $lines; | |
} | |
$text = file_get_contents('php://stdin'); | |
print count(parse($text)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment