Get a cell type using PHPExcel - phpexcel

Hi I have this code to read form excel file and add to database using joomla
try
{
$inputFileType = PHPExcel_IOFactory::identify($inputFileName);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($inputFileName);
}
catch(Exception $e) {
die('Error loading file "'.pathinfo($inputFileName,PATHINFO_BASENAME).'": '.$e->getMessage());
}
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for($i = 11; $i <= $highestRow; $i++)
{
$rowData = $sheet->rangeToArray('A' . $i . ':' . $highestColumn . $i,
NULL,
TRUE,
True
);
$row = $rowData[0];
$valeur1 = $row[8];
}
I open the file and I read it each row and for each row I read each cell
well some time the row[8] is a formated number for exemple (100100.5) some times not like (100,100.5) or something else
Well I need to know the cell type to make some change if the cell is not a number.

Using
$rowData = $sheet->rangeToArray(
'A' . $i . ':' . $highestColumn . $i,
NULL,
True,
False
);
will give you raw values back from the range rather than formatted values
Alternatively, for an individual cell, you can use
$sheet->getCell('A8')->getDataType();
to get the actual datatype stored in the cell. The list of datatypes is defined in Classes/PHPExcel/Cell/DataType.php
const TYPE_STRING2 = 'str';
const TYPE_STRING = 's';
const TYPE_FORMULA = 'f';
const TYPE_NUMERIC = 'n';
const TYPE_BOOL = 'b';
const TYPE_NULL = 'null';
const TYPE_INLINE = 'inlineStr'; // Rich text
const TYPE_ERROR = 'e';

Related

PhpSpreadsheet - get row without iterating on each cell

I'm using PhpSpreadsheet to easily read from a xls document and insert into a DB after some calculations. I succeeded using examples from the documentation, but I find it sooo complicated I'm sure I missed something and it can be done much more easily.
$worksheet = $this->getWorksheet("file.xls");
foreach ($worksheet->getRowIterator() as $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE);
foreach ($cellIterator as $key => $cell) {
$cellValue = $cell->getValue();
if($key == 'A')
$field1 = $cellValue;
if($key == 'B') {
$dateTime = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
$date = $dateTime->format("Y-m-d");
}
if($key == 'C')
$field2 = $cellValue;
if($key == 'D')
$field3 = $cellValue;
if($key == 'E')
$field4 = $cellValue;
}
}
I would have expected something like $row->getCell("A")->getValue() to be available.
So... Have I missed something ?
See the docs on getting the values by column and row directly rather than testing the keys
From the example:
// Get the value from cell B5
$cellValue = $spreadsheet->getActiveSheet()->getCellByColumnAndRow(2, 5)->getValue();
Hope that helps
Here is what I found
$reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
$spreadsheet = $reader->load("test.xlsx");
$sheet = $spreadsheet->getSheet(0);
$nb = 0;
foreach ($sheet->getRowIterator() as $row) {
echo $sheet->getCell("A$nb")->getValue();
echo "<hr>";
$nb++;
}
You have to access somehow each cell.
Example: for the case when you don't know the dimensions of rows and columns ( ... which can have combined letters past single alphabet letters), get iteration for each row and then for each column, and in the end you can have the data parsed into multidimensional array:
$results = [];
$reader = new Xlsx(); // PhpOffice\PhpSpreadsheet\Reader\Xlsx
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load(storage_path('app/temp/' . $file));
$sheet = $spreadsheet->getActiveSheet();
foreach ($sheet->getRowIterator() as $index => $row) {
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells, even if a cell value is not set.
$row_content = [];
foreach ($cellIterator as $cell) {
array_push($row_content, $cell->getValue());
}
$results[] = $row_content;
}

How to get all data from easyui datagrid

I had try to use the getData e.g.
data = $("#dg").datagrid("getData");`
var total = data.total; (total is 100)`
var rows = data.rows; (rows.length is 25)`
It can result: the total number is correct like 100 records
but the rows return only get the current page rows like 25 rows.
I need to get all of the records (100 rows).
Is there something i missed ? Or how can we do this ? Please help me.
This is because of pagination. let me describe model with pagination for showing 100 row in php.
function get_invoiceinfoList($search_keyword,$custID){
$page = 1;
$rows = 100;
$sort = '';
$order = 'asc';
$offset = ($page - 1) * $rows;
if($custID > 0 && $search_keyword == 0){
$search = " and a.customer_id =$custID";
}else{
$search = "and (b.name like '%$search_keyword%' || a.inv_no like '%$search_keyword%')" ;
}
$vQuery=$this->db->query("SELECT a.inv_id,a.inv_no,a.inv_org,a.inv_date,
a.customer_id,a.heading,a.quot_id,a.total_cost as total_amount,
a.paid_amount,(a.total_cost-a.paid_amount)as due_amount,b.name
from sales_invoice a,view_customer_info b
where
a.customer_id = b.customer_id $search order by a.inv_date DESC limit $offset, $rows");
$result = $vQuery->result();
$rows = array();
foreach ($result as $rowData){
array_push($rows, $rowData);
}
$data['rows'] = $rows;
return $data;
}

Circular References in PHPExcel - infinite loop or wrong result

I am using PHPExcel 1.8.0
I have read the posts regarding circular references, such as this one, but I am still running into issues.
If a spreadsheet contains one circular ref. formula, PHPExcel's calculations do not match MS Excel.
If a spreadsheet contains more than one circular ref, then PHPExcel goes into an infinite loop.
Here are the details of what I've done so far.
Assume a spreadsheet where A1 = B1 and B1 = A1+1, and Excel is set to 100 iterations. Here is my code:
// create reader
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
// load workbook
$objPHPExcel = $objReader->load($this->_path);
// set iterative calculations max count
PHPExcel_Calculation::getInstance($objPHPExcel)->cyclicFormulaCount = 100;
// calculate
$objWorksheet = $objPHPExcel->getSheetByName('Testing');
$data = $objWorksheet->rangeToArray('A1:B1');
echo '<pre>';
print_r ($data);
echo '</pre>';
// release resources
$objPHPExcel->disconnectWorksheets();
unset($objPHPExcel);
MSExcel results in A1 = 99, B1 = 100. My code produces this:
Array
(
[0] => Array
(
[0] => #VALUE!
[1] => #VALUE!
)
)
Further to that, if I add A2 = B2 and B2 = A2+1, and attempt to calculate (A1:B2), it goes into an infinite loop and eventually crashes:
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 24 bytes) in C:\xampp\htdocs\cgc\bulldog\application\third_party\PHPExcel\Calculation.php on line 2837
Here is what I've done so far. In _calculateFormulaValue in Calculation.php:
Line 2383: $cellValue = ''; - this is the cause of the #Value! error. I changed that to $cellValue = 0;
Line 2400:
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
This is the cause of the infinite loop. $this->_cyclicFormulaCell does not get re-set to '' after the formula in row 1 is done, so this condition does not work for the formula in row 2.
I fixed this as follows, starting from Line 2389:
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($wsTitle.'!'.$cellID))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
} elseif (($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) &&
($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID)) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
} elseif ($this->_cyclicFormulaCell == $wsTitle.'!'.$cellID) {
++$this->_cyclicFormulaCount;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
} elseif ($this->_cyclicFormulaCell == '') {
$this->_cyclicFormulaCell = $wsTitle.'!'.$cellID;
if ($this->_cyclicFormulaCount >= $this->cyclicFormulaCount) {
// Olga - reset for next formula
$this->_cyclicFormulaCell = '';
return $cellValue;
}
}
After these fixes, if I run $data = $objWorksheet->rangeToArray('A1:B2');, I get the following result:
Array
(
[0] => Array
(
[0] => 100 // should be 99
[1] => 100
)
[1] => Array
(
[0] => 100 // should be 99
[1] => 100
)
)
As you can see, the results from PHPExcel are not consistent with MS Excel. Why is this happening and how can I get around this?
Ok, I managed to debug this. My spreadsheet was very complicated, lots of circular refs. The most challenging is a scenario where A depends on B, B depends on both A and C, and C depends on B.
I also added a maxChange parameter, so the thing works like Excel. Otherwise it takes too long on my spreadsheet.
Anyway, here is a usage example:
$objPHPExcel = PHPExcel_IOFactory::load($path);
$objCalc = PHPExcel_Calculation::getInstance($objPHPExcel);
$objCalc->cyclicFormulaCount = 100;
$objCalc->maxChange = 0.001;
The two files that were modified are: Calculation.php and CalcEngine/CyclicReferenceStack.php
Here is the code (sorry Mark, I can't afford more time to submit it to git properly).
Calculation.php
add these to class properties:
private $_precedentsStack = array();
public $maxChange = 0;
replace _calculateFormulaValue() function with this:
public function _calculateFormulaValue($formula, $cellID=null, PHPExcel_Cell $pCell = null) {
$this->_debugLog->writeDebugLog("BREAKPOINT: _calculateFormulaValue for $cellID");
// Basic validation that this is indeed a formula
// We simply return the cell value if not
$formula = trim($formula);
if ($formula{0} != '=') return self::_wrapResult($formula);
$formula = ltrim(substr($formula,1));
if (!isset($formula{0})) return self::_wrapResult($formula);
// initialize values
$pCellParent = ($pCell !== NULL) ? $pCell->getWorksheet() : NULL;
$wsTitle = ($pCellParent !== NULL) ? $pCellParent->getTitle() : "\x00Wrk";
$key = $wsTitle.'!'.$cellID;
$data = array(
'i' => 0, // incremented when the entire stack has been calculated
'j' => 0, // flags the formula as having been calculated; can only be 0 or 1
'cellValue' => $pCell->getOldCalculatedValue(), // default value to start with
'precedents' => array(),
'holdValue' => FALSE // set to TRUE when change in value is less then maxChange
);
// add this as precedent
$this->_precedentsStack[] = $key;
// if already been calculated, return cached value
if (($cellID !== NULL) && ( $this->getValueFromCache($wsTitle, $cellID, $cellValue))) {
return $cellValue;
}
$this->_cyclicReferenceStack->getValueByKey($key, $data);
extract($data);
$this->_debugLog->writeDebugLog("iteration # $i");
// if already calculated in this iteration, return the temp cached value
if ($i >= $this->cyclicFormulaCount || $j == 1) {
return $cellValue;
}
// on stack, but has not yet been calculated => return default value
if (($wsTitle{0} !== "\x00") && ($this->_cyclicReferenceStack->onStack($key))) {
if ($this->cyclicFormulaCount <= 0) {
return $this->_raiseFormulaError('Cyclic Reference in Formula');
}
return $cellValue;
}
// calculate value recursively
$this->_cyclicReferenceStack->push($key);
$cellValue = $this->_processTokenStack($this->_parseFormula($formula, $pCell), $cellID, $pCell);
$this->_cyclicReferenceStack->pop();
// everything in precedent stack after the current cell is a precedent
// and every precedent's precedent is a precedent (aka a mouthfull)
while ( $this->_precedentsStack[ count($this->_precedentsStack) - 1 ] != $key ){
$data['precedents'][] = array_pop($this->_precedentsStack);
}
$data['precedents'] = array_unique($data['precedents']);
// check for max change
$oldValue = $this->_extractResult($data['cellValue']);
$newValue = $this->_extractResult($cellValue);
$data['cellValue'] = $cellValue;
$data['holdValue'] = (abs($oldValue - $newValue) < $this->maxChange);
// flag as calculated and save to temp storage
$data['j'] = 1;
$this->_cyclicReferenceStack->setValueByKey($key, $data);
// if this cell is a precedent, trigger a re-calculate
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
if ( $tempData['holdValue'] == TRUE && ( in_array($key, $tempData['precedents'])) ) {
$tempData['holdValue'] = FALSE;
}
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
// at the end of the stack, increment the counter and flag formulas for re-calculation
if (count($this->_cyclicReferenceStack->showStack()) == 0) {
$i++;
$this->_precedentsStack = array();
$tempCache = $this->_cyclicReferenceStack->showValues();
foreach ($tempCache as $tempKey => $tempData) {
$tempData['i'] = $i;
if ( ! $tempData['holdValue'] ) $tempData['j'] = 0;
$this->_cyclicReferenceStack->setValueByKey($tempKey, $tempData);
}
$this->_debugLog->writeDebugLog("iteration # $i-1 finished");
}
if ($i < $this->cyclicFormulaCount) {
$cellValue = $this->_calculateFormulaValue($pCell->getValue(), $cellID, $pCell);
} elseif ($cellID !== NULL) {
// all done: move value from temp storage to cache
$this->saveValueToCache($wsTitle, $cellID, $cellValue);
$this->_cyclicReferenceStack->removeValueByKey($key);
}
// Return the calculated value
return $cellValue;
} // function _calculateFormulaValue()
add this helper function:
private function _extractResult($result) {
if (is_array($result)) {
while (is_array($result)) {
$result = array_pop($result);
}
}
return $result;
}
CyclicReferenceStack.php
add a property:
private $_values = array();
add a bunch of functions:
public function setValueByKey($key, $value) {
$this->_values[$key] = $value;
}
public function getValueByKey($key, &$value) {
if (isset($this->_values[$key])) {
$value = $this->_values[$key];
return true;
}
return false;
}
public function removeValueByKey($key) {
if (isset($this->_values[$key])) {
unset($this->_values[$key]);
}
}
public function showValues() {
return $this->_values;
}

helpme to recognize that kind of date is and convert mysql date with PHPExcel

I have a problem I'm generating an array with PHPExcel but to insert the date on the base gives an error because the date is in excel format and need mysql here is the code used
$objReader = new PHPExcel_Reader_Excel2007();
$objPHPExcel = $objReader->load( $targetFile );
$objPHPExcel->setActiveSheetIndex(0);
$lastRow = $objPHPExcel->getActiveSheet()->getHighestRow();
$dataExcel = array();
for ( $i = 2; $i <= $lastRow; $i++ ){
$dataExcel[$i]['usr_date_entry'] = $objPHPExcel->getActiveSheet()->getCell('K'.$i)->getCalculatedValue();
}
´echo $dataExcel[0]['usr_date_entry']; // return 21774´

Changing a long imperative block of code into a more functional programming style

I am new to functional programming and I want to learn how to structure my programs by composing functions (so that I can choose which ones to use a-la-carte based on my needs)
I have a long block of imperative code that goes like this in pseudo-code:
function do_complicated_stuff(input) {
//do some DB stuff and get information about A,B,C,D
//prepare Output A
//prepare Output B
//prepare Output C
//prepare Output D
if(condition) {
A = "I am A1"
B = "I am B1"
C = "I am C1"
D = "I am D1"
} else {
//do the same as above, but change to I am A2, B2, C2, D2
}
array = {A, B, C, D};
return array;
}
Is there a way to write this as function application instead of imperative code? Things I want to simplify: I don't want to handle A, B, C, D explicitly so I don't want to make function calls like do_other_stuff(A, B, C, D, db_stuff_required_for_A, db_stuff_required_for_B)
So clearly I want to have a function like do_other_stuff(one_item), but the eventual return value should be something like "I am A1" if one_item is A and condition is true and "I am B2" if condition is false and one_item is B.
I know how I would do this in an OOP way, I guess I'd have a bunch of objects that know what to do with their own data where I just need to call item.other_stuff() and it figures it out. How would I write the same thing in a more functional style, composing many short functions that do one thing to give me the desired "I am L#" result in the end? Note that you need different DB information for each of the eight cases that sometimes overlaps and is sometimes completely different between each case. So it's currently very complected and not very simple, since the function in my current code is over 100 lines and handles all eight cases explicitly. Worse, the same thing is done again in a different way with a different output format like "This is A1" somewhere else. So I'd like to separate the output from the processing and from the DB calls. Let's assume I could pick any language to re-implement this in, so take any functional feature you want. How would I do this and which abstractions/language features do I need?
Brace yourself, this is the ACTUAL php code and it's not pretty and handles only half of the cases (but I want to extend it to cover everything, of course, instead of using the old code)
function do_complicated_stuff(Buysellitem $item) {
$result = new stdClass();
global $user_currency;
$curr_obj = get_cached('getCurrenciesDAO', 'load', array($item->currencyID));
$price = CurrencyConverter::convert($curr_obj->abbr, $user_currency->abbr, $item->price);
$dollarPrice = CurrencyConverter::convert($curr_obj->abbr, 'USD', $item->price);
$item_cat_id = $item->categoryId;
if(!empty($item_cat_id)) {
$item_cat = DAOFactory::getCategoryDetailsDAO()->load($item_cat_id)->categoryNameEn;
}
$designer_obj = DAOFactory::getUsersDAO()->load($item->userID);
$item_images = DAOFactory::getBuysellitemimagesDAO()->queryByBuySellID($item->buySellID);
foreach($item_images as $cur_image) {
if($cur_image->isDefault) {
if(!empty($cur_image->aspectRatio) && $cur_image->aspectRatio > 0){
$main_image_height = round(498 / $cur_image->aspectRatio);
$main_image = DOMAIN . SELLIMG_PATH .
File_Controller::getImage($cur_image->buySellItemImagePath, 498, $main_image_height);
}else{
$main_image = '';
}
}
}
$designerName = decode_entities($designer_obj->companyName);
$trim_cat = !empty($item_cat) ? ' #' . strtolower(preg_replace('/\s+/', '', $item_cat)) : '';
$desc = decode_entities($item->description);
$trim_desc = str_short($desc, SHARE_LENGTH);
$item_link = SHARE_ITEM_LINK . $item->buySellID;
$item_name = str_short(decode_entities($item->buySellName), TW_SHARE);
if(!empty($price)) {
$decimals = $price < 10 ? 2 : 0;
$dollarDecimals = $price < 10 ? 2 : 0;
$priceFormatted = number_format($price, $decimals, '.', '');
$dollarPriceFormatted = number_format($dollarPrice, $dollarDecimals, '.', '');
//if the currency is SEK it doesn't have a sign, so show the abbreviation instead
$curr_abbr = empty($curr_obj->sign) ? $curr_obj->abbr : '';
$price_tag = ($item->discount > 0) ?
", at {$item->discount}% off":
" - {$curr_obj->sign}$priceFormatted$curr_abbr";
$d_price_tag = ($item->discount > 0) ?
", at {$item->discount}% off":
" - \$$dollarPriceFormatted";
} else {
$price_tag = '';
$d_price_tag = '';
}
$text = "{$item_name}$price_tag by $designerName";
$pi_html = "$item_link \n {$item_name}$d_price_tag by $designerName \n $trim_desc";
$tw_text = "$text$trim_cat #design";
$tu_html = "<a href='$item_link'><strong>$text</strong></a><br/>$desc";
$result->facebook = new stdClass();
$result->twitter = new stdClass();
$result->tumblr = new stdClass();
$result->pinterest = new stdClass();
if(empty($item->video)) {
$result->facebook->link = FB_LINK . '?' . http_build_query(array(
'u'=>$item_link,
'display'=>'popup',
'redirect_uri'=>FACEBOOK_TRACK
), '', '&');
$result->twitter->link = TW_LINK . '?' . http_build_query(array(
'original_referrer'=> DOMAIN . $_SERVER['PHP_SELF'],
'url'=>$item_link,
'related'=>'CityBlis',
'via'=>'CityBlis',
'text'=>$tw_text
), '', '&');
$result->tumblr->link = TU_LINK . '?' . http_build_query(array(
'source'=>$main_image,
'caption'=>$tu_html,
'clickthru'=> $item_link
), '', '&');
$result->pinterest->link = PI_LINK . '?' . http_build_query(array(
'url'=>$item_link,
'media'=>$main_image,
'description'=>$pi_html
), '', '&');
} else {
$video_link = youtube_vimeo($item->video);
$result->facebook->link = FB_LINK . '?' . http_build_query(array(
'link'=>$item_link,
'display'=>'popup',
'source'=>$video_link,
'picture'=>$main_image,
'redirect_uri'=>FACEBOOK_TRACK
), '', '&');
$result->twitter->link = TW_LINK . '?' . http_build_query(array(
'original_referrer'=> DOMAIN . $_SERVER['PHP_SELF'],
'url'=>$item_link,
'related'=>'CityBlis',
'via'=>'CityBlis',
'text'=>$tw_text
), '', '&');
$result->tumblr->link = TU_LINK . '?' . http_build_query(array(
'embed'=>$video_link,
'caption'=>$tu_html
), '', '&');
$result->pinterest->link = PI_LINK . '?' . http_build_query(array(
'url'=>$video_link,
'media'=>$main_image,
'description'=>$pi_html,
'is_video'=>'true'
), '', '&');
}
return $result;
}
function inline_product_share($input) {
$item = do_complicated_stuff($input);
$item->facebook->title = FB_TITLE;
$item->facebook->innerStyle = '';
$item->facebook->dimensions = '';
$item->facebook->follow = '';
$item->twitter->title = TW_TITLE;
$item->twitter->innerStyle = '';
$item->twitter->dimensions = '';
$item->twitter->follow = '';
$item->tumblr->title = TU_TITLE;
$item->tumblr->innerStyle = '';
$item->tumblr->dimensions = '';
$item->tumblr->follow = '';
$item->pinterest->title = PI_TITLE;
$item->pinterest->innerStyle = '';
$item->pinterest->dimensions = '';
$item->pinterest->follow = '';
return order_output($item);
}
//does the ordering of the output and returns the resultant string
function order_output($item) {
$style_string = "position:relative;display:inline-block;width:25px;height:25px;
overflow:hidden;margin-left:4px;vertical-align:top;border-radius:17px;
background-image: url(\"/i/iSpr.png\");"; //TODO: make it an absolute path when we put it up
$style = " style='$style_string;";
$item->facebook->style = $style . "background-color:#3c5897;background-position:-28px 0px;'";
$item->twitter->style = $style . "background-color:#2daae0;background-position:-55px 0px;'";
$item->tumblr->style = $style . "background-color:#2a4361;background-position:-82px 0px;'";
$item->pinterest->style = $style . "background-color:#ca1f25;background-position:-108px 0px;'";
return output_item($item->facebook) .
output_item($item->twitter) .
output_item($item->tumblr) .
output_item($item->pinterest);
}
//its only responsibility is to accept an object to return the output html
function output_item($item) {
ob_start();
?><div<?php echo $item->style?>><a target="_blank" title="<?php
echo $item->title?>"<?php
echo $item->innerStyle?> href="<?php
echo $item->link
?>"<?php
echo $item->follow?><?php
echo $item->dimensions?>><?php
echo $item->title?></a></div><?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
I don't belive I got enough information to hit the nail on the head since you didn't say anything about the nature of A, B, C and D. However, if they are anything like sub classes and we want to perform some kind of operation on all of them that are inherited we have the iam function that treats them similar. The condition I don't know where came from so I added it as an argument and in the anonymous function index, which is derievd from condition, is's closed in from the scope of which the function is created.
function iam(item, index)
{
return "I am " . item . index; // Might be more advanced than this
}
function do_complicated_stuff(input, condition) {
array_of_abcd = db_readabcd(input);
index = (condition ? 1 : 2);
handle = function(item)
{
// function has index as free variable
return iam( item, index );
}
// Use map to iterate over the elelemts of the array
// applying handle on each one
return map(handle array_of_abcd);
}
This example shows two properties of functional programming. Closures and higher order functions. Here is the same in Scheme:
(define (iam item index)
(string-append "I am "
item
index))
(define (do-complecated-stuff input condition)
(let ([array-of-abcd (db-readabcd input)] ; get data
[index (number->string (if condition 1 2))]) ; get index
; use map to iterate over elements with an anonymous function
(map (lambda (item) (iam item index)) array-of-abcd)))

Resources