How I can delete an item …

How I can delete an item in an array ?

Short Answer : We have a special function : ADel()
Long Answer :

ADel() function may cause some confusions when documentation not read carefully:

This function deletes the element found at the given subscript position in the array.

All elements in the array below the given subscript position will move up one positionin the array.

 

Let’s try:

?
 aTest1 := { 'One', 'Two', "Tree",'Four' }
 aTest := ACLONE( aTest1 )
 ADel( aTest, 3 )
 ? LEN( aTest )
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 
 

Result :
4
One Two Four NIL
Length of array not changed, last item moved up and new last item became NIL.

 

?
 ASIZE( aTest, 3 )
 ? LEN( aTest )
 ?
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } )

Result :
3
One Two Four
Length of array changed, last item (NIL) removed

We have another possibility: a new Harbour function:

?
 aTest1 := { 'One', 'Two', "Tree",'Four' }
 aTest := ACLONE( aTest1 )
 HB_ADel( aTest, 3 )
 ? LEN( aTest )
 ?
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } )
 

Result :
4
One Two Four NIL
Length of array not changed, last item moved up and new last item became NIL.
Same as ADel()

And we have a third parameter : Shrink or not:

 ?
 aTest1 := { 'One', 'Two', "Tree",'Four' }
 aTest := ACLONE( aTest1 )
 HB_ADel( aTest, 3, .T. )
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } )

That’s all !

 

How I can insert a new …

How I can insert  a new item to an array ?

Short answer : We have a special function : AIns()
Long Answer :

AIns() function may cause some confusions when documentation not read carefully:

This function inserts a NIL value in the array named <aArray> at the <nPos>th position.

All array elements starting with the <nPos>th position will be shifted down one subscript position in the array list and the last item in the array will be removed completely.

 

Let’s try:

 aTest := { 'One', 'Two', 'Four' }
 AIns( aTest, 3 ) 
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 
 

Result : One Two NIL: “Four” lost !

Since it’s NIL, we can assign a value to it:

 aTest := { 'One', 'Two', 'Four' }
 AIns( aTest, 3 )
 aTest[ 3 ] := "Three"
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 
 

Result : One Two Three: “Four” lost !

Before insert we can add a dummy item to end of array:

 aTest := { 'One', 'Two', 'Four' }
 AADD( aTest, NIL )
 AIns( aTest, 3 )
 aTest[ 3 ] := "Three"
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 
 

Result : One Two Three Four : OK
Or we can change size of array :

 aTest := { 'One', 'Two', 'Four' }
 ASIZE( aTest, 4 )
 AIns( aTest, 3 )
 aTest[ 3 ] := "Three"
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 
 

Result : One Two Three Four : OK

But wait; we have another possibility: a new Harbour function:

 aTest := { 'One', 'Two', 'Four' }
 HB_AIns( aTest, 3, "Three" )
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 

Result : One Two Three: “Four” lost !

And we have a fourth parameter : Grow or not:

 aTest := { 'One', 'Two', 'Four' }
 HB_AIns( aTest, 3, "Three", .T. )
 AEVAL( aTest, { | c1 | QQOUT( c1, '' ) } ) 
 

Result : One Two Three Four

That’s all !

SP_ALENG

ALENG()

  Short:
  ------
  ALENG() Actual length of an array, less trailing nil elements

  Returns:
  --------
  <aLength>  => Actual array length, less trailing NILs

  Syntax:
  -------
  ALENG(aTarget)

  Description:
  ------------
  Determines the actual length of <aTarget>, less
  trailing nils.

  Examples:
  ---------

   a := {1,2,3,4,5,nil,nil,nil}
   ?len(a)       // => returns 8
   ?aleng(a)     // => returns 5

  Notes:
  ------
  This was a C function in prior Super.Libs

  Source:
  -------
  S_ALENG.PRG

 

Hash Basics

Definition:

In general, a Hash Table, or Hash Array, or Associative array, or shortly Hash is an array- like data structure, to store some data with an associated key for each; so, ‘atom’ of a hash is a pair of a ‘key’ with a ‘value’. A hash system needs to perform at least three operations:

–      add a new pair,

–      access to value via key

–      the search and delete operations on a key pair

In Harbour, a hash is simply a special array, or more precisely a “keyed” array with special syntax with a set of functions.

Building:

The “=>” operator can be used to indicate literally the relation between <key> <value> pair: <key> => <value>

 We can define and initialize a hash by this “literal” way :

 hDigits_1 := { 1 => 1, 2  => 2, 3  => 3, 4  => 4 }

 or by a special function call:

 hDigits_1 := HB_HASH( 1, 1, 2, 2, 3, 3, 4, 4 )

 Using “add” method may be another way :

hDigits_1 := { => } // Build an empty hash
hDigits_1[ 1] := 1

hDigits_1[ 2] := 2

hDigits_1[ 3] := 3

hDigits_1[ 4] := 4

In this method while evaluating each of above assignments, if given key exits in hash, will be replaced its value; else add a new pair to the hash.

In addition, data can be added to a hash by extended “+=” operator:

   hCountries := { 'Argentina' => "Buenos Aires" }
   hCountries += { 'Brasil'    => "Brasilia" }
   hCountries += { 'Chile'     => "Santiago" }
   hCountries += { 'Mexico'    => "Mexico City" }

Hashs may add ( concatenate ) each other by extended “+” sign :

   hFruits := { "fruits" => { "apple", "chery", "apricot" } }
   hDays   := { "days"   => { "sunday", "monday" } } 
   hDoris := hFruits + hDays

Note:  This “+” and “+=” operators depends xHB lib and needs to xHB lib and xHB.ch.

Typing :

<key> part of a hash may be any legal scalar type : C, D, L, N; and <value> part may be in addition scalar types, any complex type ( array or hash ).

Correction : This definition is wrong ! The correct is :

<key> entry key; can be of type: number, date, datetime, string, pointer.

Corrected at : 2015.12.08; thanks to Marek.

hDigits_2 := {  1  => “One”,  2  => “Two”,  3  => “Three”,  4  => “Four” }

hDigits_3 := { "1" => "One", "2" => "Two", "3" => "Three", "4" => "Four" }
hDigits_4 := { "1" => "One",  2  => "Two",  3  => "Three", "4" => "Four" }
hDigits_5 := {  1  => "One",  1  => "Two",  3  => "Three",  4  => "Four"

All of these examples are legal. As a result, a pair record of a hash may be:

–      Numeric key, numeric value ( hDigits_1 )

–      Numeric key, character value ( hDigits_2 )

–      Character key, character value ( hDigits_3 )

–      Mixed type key ( hDigits_4 )

Duplicate keys (as seen in hDigits_5) is permitted to assign, but not give a result such as double keyed values: LEN( hDigits_5 ) is 3, not 4; because first pair replaced by second due to has same key.

Consider a table-like data for customers records with two character fields: Customer ID and customer name:

Cust_ID Cust_Name
CC001 Pierce Firth
CC002 Stellan Taylor
CC003 Chris Cherry
CC004 Amanda Baranski

We can build a hash with this data :

  hCustomers := { "CC001" => "Pierce Firth",;
 "CC002" => "Stellan Taylor",;
 "CC003" => "Chris Cherry",;
 "CC004" => "Amanda Baranski" }

and list it:

   ?
   ? "Listing a hash :"
   ?
   h1Record := NIL
   FOR EACH h1Record IN hCustomers
      ? cLMarj, h1Record:__ENUMKEY(), h1Record:__ENUMVALUE()
   NEXT

 Accessing a specific record is easy :

 hCustomers[ "CC003" ] // Chris Cherry
*-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.
/*
Hash Basics

*/
#include "xhb.ch"
#define NTrim( n ) LTRIM( STR( n ) )
PROCEDURE Main()
 SET DATE GERM
 SET CENT ON
 SET COLO TO "W/B"

 cLMarj := SPACE( 3 )

 CLS

 hDigits_1 := { => } // Build an empty hash

 hDigits_1[ 1 ] := 1
 hDigits_1[ 2 ] := 2
 hDigits_1[ 3 ] := 3
 hDigits_1[ 4 ] := 4

 ListHash( hDigits_1, "Digits_1" )

 hDigits_2 := HB_HASH( 1, 1, 2, 2, 3, 3, 4, 4 )

 ListHash( hDigits_2, "Digits_2" )

 hDigits_3 := { 1 => 1,;
 2 => 2,;
 3 => 3,;
 4 => 4 }
 ListHash( hDigits_3, "Digits_3" )

 hDigits_4 := { 1 => "One",;
 2 => "Two",;
 3 => "Three",;
 4 => "Four" }
ListHash( hDigits_4, "Digits_4" )

 hDigits_5 := { "1" => "One",;
 "2" => "Two",;
 "3" => "Three",;
 "4" => "Four" }
 ListHash( hDigits_5, "Digits_5" )

 hDigits_6 := { "1" => "One",;
 2 => "Two",;
 3 => "Three",;
 "4" => "Four" }
 ListHash( hDigits_6, "Digits_6" )

 hDigits_7 := { 1 => "One",;
 1 => "Two",; // This line replace to previous due to same key 
 3 => "Three",;
 4 => "Four" }
 ListHash( hDigits_7, "Digits_7" )

 * WAIT "EOF digits"

 hCustomers := { "CC001" => "Pierce Firth",;
 "CC002" => "Stellan Taylor",;
 "CC003" => "Chris Cherry",;
 "CC004" => "Amanda Baranski" }
 ListHash( hCustomers, "A hash defined and initialized literally" )
 ?
 ? "Hash value with a specific key (CC003) :", hCustomers[ "CC003" ] // Chris Cherry
 ?
 cKey := "CC003" 
 ?
 ? "Locating a specific record in an hash by key (", cKey, ":"
 ?
 c1Data := hCustomers[ cKey ]
 ? cLMarj, c1Data

 hCountries := { 'Argentina' => "Buenos Aires" }
 hCountries += { 'Brasil' => "Brasilia" }
 hCountries += { 'Chile' => "Santiago" }
 hCountries += { 'Mexico' => "Mexico City" }

 ListHash( hCountries, "A hash defined and initialized by adding with '+=' operator:" )

 hFruits := { "fruits" => { "apple", "chery", "apricot" } }
 hDays := { "days" => { "sunday", "monday" } } 

 hDoris := hFruits + hDays

 ListHash( hDoris, "A hash defined and initialized by concataned two hash with '+' operator:" )

 ?
 @ MAXROW(), 0
 WAIT "EOF HashBasics.prg"

RETURN // HashBasics.Main()
*-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.
PROCEDURE ListHash( hHash, cComment )

 LOCAL x1Pair := NIL

 cComment := IF( HB_ISNIL( cComment ), '', cComment )

 ? 
 ? cComment, "-- Type :", VALTYPE( hHash ), "size:", NTrim ( LEN( hHash ) ) 
 ?
 FOR EACH x1Pair IN hHash
    nIndex := x1Pair:__ENUMINDEX()
    x1Key := x1Pair:__ENUMKEY()
    x1Value := x1Pair:__ENUMVALUE()
    ? cLMarj, NTrim( nIndex ) 
*   ?? '', VALTYPE( x1Pair )
    ?? '', x1Key, "=>"
*   ?? '', VALTYPE( x1Key ) 
*   ?? VALTYPE( x1Value ) 
    IF HB_ISARRAY( x1Value ) 
       AEVAL( x1Value, { | x1 | QQOUT( '', x1 ) } )
    ELSE 
       ?? '', x1Value
    ENDIF 
 NEXT

RETURN // ListHash()
*-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.

HashBass

Multi-Dimensional Arrays

Since elements of an array may be any data type, may be also an array. And when any element of an array is an array, it called multi-dimensional array.

As cited in array-basics, multi-dimensional array too subscripted like single dimension array. Only difference is specifying separate subscript for each dimension. This is correct for both defining and retrieving.

For example:

aArray2D := ARRAY( 2, 3 )
? HB_ValToExp( aArray2D )  // {{NIL, NIL, NIL}, {NIL, NIL, NIL}}
aArray2D := { { 1, 2, 3 }, { 4, 5, 6 } }
? HB_ValToExp( aArray2D )  // {{1, 2, 3}, {4, 5, 6}}

A multi-dim array doesn’t have to be “uniform”; any element of an array may be an array :

aArrMDim := { 1, "One", DATE(), .T., { 1, 2, 3, 4 } }
? HB_ValToExp(aArrMDim )  // {1, "One", 0d20130108, .T., {1, 2, 3, 4}}

In such case we can’t talk about aArrMDim[ 1, 1 ], aArrMDim[ 3, 2 ], … only aArrMDim[ 5, 1 ], aArrMDim[ 5, 2 ], …

Since fifth element of aArrMDim is a array, we can any array operation on it:

ASIZE( aArrMDim[ 5 ], 2 )
? HB_ValToExp(aArrMDim[ 5 ] )  // {1, 2}
? LEN( aArrMDim[ 5 ] )         // 2

Language doesn’t enforce any rules on what can be stored in an array; this level of control must be implemented programmatically.

The fact that you can assign an array ( or any data type else ) to an existing array element allows you to dynamically change structure of an array. For example, after an array built there is nothing prevent you from doing something like this:

aArrMDim[ 2 ] := { 2.5, 5.75, 3.14 }

This statement change second element of array from string to array. Now, aArrMDim[ 2, 3 ], aArrMDim[ 5, 3 ] are valid, but aArrMDim[ 3, 1 ] result a runtime error.

This feature of assigning an array reference to an array element can come in handy in lot of applications. The thing to remember is that you as the programmer must exercise whatever control you think is necessary for storing and addressing array elements. You cannot make any assumption about the structure of an array unless you enforce that structure.

PROCEDURE Main()
   ?
   ? "Multi-dim arrays :"
   ?

   aArray2D := ARRAY( 2, 3 )
   ShowValue( aArray2D, "two-dim"  )
   Show2DArr( aArray2D )

   aArray2D := { { 1, 2, 3 }, { 4, 5, 6 } }
   ShowValue( aArray2D, "two-dim"  )
   Show2DArr( aArray2D )

   aArrMDim := { 1, "One", DATE(), .T., { 1, 2, 3, 4 } }
   ShowValue( aArrMDim, "Multi-dim"  )

   ? "Before ASIZE() :", LEN( aArrMDim )
   ASIZE( aArrMDim[ 5 ], 2 )
   ShowValue( aArrMDim, "Shrinked subarray"  )
   ? "After ASIZE() :", LEN( aArrMDim )
   ? HB_ValToExp(aArrMDim[ 5 ] )  // {1, 2}
   ? LEN( aArrMDim[ 5 ] ) //
   ShowValue( aArrMDim, "Shrinked"  )

   ?
   @ MAXROW(), 0
   WAIT "EOF MD_Arrays.prg"

RETURN // MD_Arrays.Main

*-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._

PROCEDURE ShowValue( xValue, cComment )
   LOCAL cType := VALTYPE( xValue )
   ? cComment, ":",;
     ValType( xValue ),;
     IF( cType $ "CMA", HB_ValToExp( LEN( xValue ) ),''),;
     HB_ValToExp( xValue )
   ?
RETURN // ShowValue()
*-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._
PROCEDURE Show2DArr( a2DArr )
   ?
   FOR nD1 := 1 TO 2
      FOR nD2 := 1 TO 3
         ?? a2DArr[ nD1, nD2 ]
      NEXT
      ?
   NEXT
RETURN // Show2DArr()
*-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._.-._

 MD_Arrays

Array Basics

    An array is a distinct data type which may contains multiple data items under same name.  Data items stored in an array referred as an “element” and can be any data type. An individual element of array referenced by array name and position number of element as an integer in array, called “index” or “subscript”.

 Defining / Building:

    An array is a variable and like all variables has “scope”; arrays can be defined PRIVATE, PUBLIC and LOCAL as well as STATIC.

   Building an array is quite simple: for example to define an array named “aColors” with 5 elements we can use a statement like this:

LOCAL aColors[ 5 ]

or

LOCAL aColors := ARRAY( 5 )

or

LOCAL  aColors := {  , , , , }

Results of these three methods are exactly same; we can inspect easily:

? ValType( aColors )      // A

? LEN( aColors )          // 5
? HB_ValToExp( aColors )  // {NIL, NIL, NIL, NIL, NIL}

NIL is a special data type with meaning “not defined”.

We can define an array with initial value(s)

aColors := {  “green”, ”yellow” ,  “red”,  “black”, “white” }

or assign values after defined:

aColors[ 1 ] := ”green”
aColors[ 2 ] := ”yellow”
aColors[ 3 ] := ”red”
aColors[ 4 ] := ”black”
aColors[ 5 ] := ”white”
? HB_ValToExp( aColors ) // {"green", "yellow", "red", "black", "white"}

Retrieve:

As seen in our first array statement

LOCAL aColors[ 5 ]

used a special sign square brackets as “Array element indicator” ( used also as string delimiter ).

As cited at the beginning, an individual element of array is referenced by array name and position number of element as an integer (enclosed by square brackets) in array, called “index” or “subscript”, and this notation called “subscripting”.

Note that subscribing begins with one.

To specify more than one subscript ( i.e. when using multi-dimensional arrays), you can either enclose each subscript in a separate set of square brackets, or separate the subscripts with commas and enclose the list in square brackets. For example, if aArray is a two dimensional array, the following statements both addresses the second column element of tenth row:

aArray[ 10 ][ 2]
aArray[ 10, 2]

Of course it’s illegal to address an element that is outside of the boundaries of the array (lesser than one or greater than array size / length; one is also illegal for an empty array). Attempting to do so will result in a runtime error.

When making reference to an array element using a subscript, you are actually applying the subscript operator ([]) to an array expression, not only an array identifier (array variable name). An array expression is any valid expression that evaluate to an array. This includes function calls, variable references, subscripting operations, or any other expression that evaluate to an array. For example, the following are all valid:

 { “a”, “b”, “c” }[ 2 ]

x[ 2 ]
ARRAY(3)[ 2 ]
&(<macro expression>)[ 2 ]
(<complex expression>)[ 2 ]

Syntax :

 <aArrayName> [ <nSubscript> ]

<nSubscript> is integer value and indicate sequence number of element into this array.

With this way we can also traverse an array:

FOR nColor := 1 TO LEN( aColors )
     ? aColors[ nColor ]
NEXT nColor

In fact, with the other FOR loop, traversing an array doesn’t require subscripting:

cColor := “” // FOR EACH loop require a predefined loop element

FOR EACH cColor IN aColors
  ? cColor
NEXT nColor

Elements of an array may be different data type; thus arrays called as “ragged” arrays in Clipper language.

aRagged := { 1, "One", DATE(),  .T. } 
FOR nIndex := 1 TO LEN( aRagged )
   x1Elem := aRagged[ nIndex  ]
   ? VALTYPE( x1Elem ), x1Elem
NEXT nIndex

A build-in array function AEVAL() can be use instead of a loop :

AEVAL( aRagged, { | x1 | QOUT(x1 ) } )

 

Adding one element to end of an array:

The architect of array is quite versatile. Array may change ( in size and element values ) dynamically at run time.

 AADD() function can be used for add a new element to the end of an array

AADD(<aTarget>, <expValue>) --> Value

<aTarget> is the array to which a new element is to be added.

<expValue> is the value assigned to the new element.

AADD() is an array function that increases the actual length of the target array by one.  The newly created array element is assigned the value specified by <expValue>.

AADD() is used to dynamically grow an array.  It is useful for building dynamic lists or queues.

For example an array may build empty and later add element(s) to it :

aColors := {}
AADD( aColors, ”green” )
AADD( aColors, ”yellow” )
AADD( aColors, ”red” )
AADD( aColors, ”black” )
AADD( aColors, ”white” )
? HB_ValToExp( aColors ) // {"green", "yellow", "red", "black", "white"}
Inserting one element to an array:

AINS() function can be use for insert a NIL element into an array

AINS (<aTarget>, <nPosition>) --> aTarget

<aTarget> is the array into which a new element will be inserted.

<nPosition> is the position at which the new element will be  inserted.

AINS() is an array function that inserts a new element into a specified array.  The newly inserted element is NIL data type until a new value is assigned to it.  After the insertion, the last element in the array is discarded, and all elements after the new element are shifted down one position.

For a lossless AINS() ( HL_AINS() ) look at attached .prg.

Deleting one element from an array:

ADEL(<aTarget>, <nPosition>) --> aTarget

ADEL() is an array function that deletes an element from an array.  The content of the specified array element is lost, and all elements from that position to the end of the array are shifted up one element.  The last element in the array becomes NIL. So, ADEL() function doesn’t change size of array.

For an another ADEL()  ( HL_ADEL() ) look at attached .prg.

Resizing:

 ASIZE() function can be use for grow or shrink, that is changing size of an array.

ASIZE( <aTarget>, <nLength>) --> aTarget

<aTarget> is the array to grow or shrink.

<nLength> is the new size of the array.

 

     ASIZE() is an array function that changes the actual length of the   <aTarget> array.  The array is shortened or lengthened to match the specified length.  If the array is shortened, elements at the end of the array are lost.  If the array is lengthened, new elements are added to the end of the array and assigned NIL.

     ASIZE() is similar to AADD() which adds a single new element to the end   of an array and optionally assigns a new value at the same time.  Note that ASIZE() is different from AINS() and ADEL(), which do not actually      change the array’s length.

Assigning a fixed value to all elements of an array:

Changing values of all element of an array can not be accomplish by a simple assign statement. For example:

aTest := ARRAY( 3 )
aTest := 1

change type of aTest from array to numeric with a value 1.

Instead, AFILL() function gives a short way to fill an array with a fixed value.

AFILL() :  Fill an array with a specified value

Syntax :

AFILL(<aTarget>, <expValue>,
    [<nStart>], [<nCount>]) --> aTarget
    <aTarget> is the array to be filled.

<expValue> is the value to be placed in each array element.  It can be an expression of any valid data type.

<nStart> is the position of the first element to be filled.  If this argument is omitted, the default value is one.

<nCount> is the number of elements to be filled starting with  element <nStart>.  If this argument is omitted, elements are filled from the starting element position to the end of the array.

Code evaluation on an array:

AEVAL()

Execute a code block for each element in an array

Syntax:

AEVAL(<aArray>, <bBlock>,
    [<nStart>], [<nCount>]) --> aArray

Arguments:

<aArray> is the array to traverse.

<bBlock> is a code block to execute for each element encountered.

<nStart> is the starting element.  If not specified, the default is  element one.

<nCount> is the number of elements to process from <nStart>.  If not specified, the default is all elements to the end of the array.

Returns:

     AEVAL() returns a reference to <aArray>.

Description:

AEVAL() is an array function that evaluates a code block once for each element of an array, passing the element value and the element index as  block parameters.  The return value of the block is ignored.  All      elements in <aArray> are processed unless either the <nStart> or the  <nCount> argument is specified.

AEVAL() makes no assumptions about the contents of the array elements it is passing to the block.  It is assumed that the supplied block knows  what type of data will be in each element.

AEVAL() is similar to DBEVAL() which applies a block to each record of a  database file.  Like DBEVAL(), AEVAL() can be used as a primitive for  the construction of iteration commands for both simple and complex array  structures.

Refer to the Code Blocks section in the “Basic Concepts” chapter of the   Programming and Utilities Guide for more information on the theory and syntax of code blocks.

Examples :

This example uses AEVAL() to display an array of file names  and file sizes returned from the DIRECTORY() function:

#include “Directry.ch”

//

LOCAL aFiles := DIRECTORY(“*.dbf”), nTotal := 0

AEVAL(aFiles, { | aDbfFile |;
     QOUT( PADR(aDbfFile[F_NAME], 10), aDbfFile[F_SIZE]),;
     nTotal += aDbfFile[F_SIZE])} )
//
?
? "Total Bytes:", nTotal

This example uses AEVAL() to build a list consisting of  selected items from a multi-dimensional array:

#include "Directry.ch"
//
LOCAL aFiles := DIRECTORY("*.dbf"), aNames := {}
AEVAL(aFiles, { | file | AADD(aNames, file[F_NAME]) } )

This example changes the contents of the array element depending on a condition.  Notice the use of the codeblock  parameters:

 

LOCAL aArray[6]
AFILL(aArray,"old")
AEVAL(aArray,;
{|cValue,nIndex| IF( cValue == "old",;
aArray[nIndex] := "new",)})

Searching a value into an array :

ASCAN() : Scan an array for a value or until a block returns true (.T.)

Syntax:

ASCAN(<aTarget>, <expSearch>,
       [<nStart>], [<nCount>]) --> nStoppedAt

 Arguments:

<aTarget> is the array to be scanned.

<expSearch> is either a simple value to scan for, or a code block.   If <expSearch> is a simple value it can be character, date, logical, or  numeric type.

<nStart> is the starting element of the scan.  If this argument is not specified, the default starting position is one.

<nCount> is the number of elements to scan from the starting  position.  If this argument is not specified, all elements from the  starting element to the end of the array are scanned.

 Returns:

ASCAN() returns a numeric value representing the array position of the last element scanned.  If <expSearch> is a simple value, ASCAN() returns the position of the first matching element, or zero if a match is not  found.  If <expSearch> is a code block, ASCAN() returns the position of the element where the block returned true (.T.).

 Description:

ASCAN() is an array function that scans an array for a specified value and operates like SEEK when searching for a simple value.  The  <expSearch> value is compared to the target array element beginning with  the leftmost character in the target element and proceeding until there are no more characters left in <expSearch>.  If there is no match,  ASCAN() proceeds to the next element in the array.

Since ASCAN() uses the equal operator (=) for comparisons, it is  sensitive to the status of EXACT.  If EXACT is ON, the target array  element must be exactly equal to the result of <expSearch> to match.

If the <expSearch> argument is a code block, ASCAN() scans the <aTarget>   array executing the block for each element accessed.  As each element is encountered, ASCAN() passes the element’s value as an argument to the code block, and then performs an EVAL() on the block.  The scanning operation stops when the code block returns true (.T.), or ASCAN()  reaches the last element in the array.

  Examples:

This example demonstrates scanning a three-element array using simple values and a code block as search criteria.  The code block criteria show how to perform a case-insensitive search:

aArray := { "Tom", "Mary", "Sue" }
? ASCAN(aArray, "Mary")               // Result: 2
? ASCAN(aArray, "mary")               // Result: 0
//
? ASCAN(aArray, { |x| UPPER(x) == "MARY" }) // Result: 2

This example demonstrates scanning for multiple instances of a search argument after a match is found:

LOCAL aArray := { "Tom", "Mary", "Sue","Mary" },; 
      nStart := 1
//
// Get last array element position
nAtEnd := LEN(aArray)
DO WHILE (nPos := ASCAN(aArray, "Mary", nStart)) > 0
   ? nPos, aArray[nPos]
   //
   // Get new starting position and test
   // boundary condition
   IF (nStart := ++nPos) > nAtEnd
      EXIT
   ENDIF
ENDDO

This example scans a two-dimensional array using a code block.  Note that the parameter aVal in the code block is an array:

LOCAL aArr:={}
CLS
AADD(aArr,{"one","two"})
AADD(aArr,{"three","four"})
AADD(aArr,{"five","six"})
? ASCAN(aArr, {|aVal| aVal[2] == "four"})         // Returns 2

Sorting an array:

ASORT() :  Sort an array

Syntax:

ASORT(<aTarget>, [<nStart>],
[<nCount>], [<bOrder>]) --> aTarget

 Arguments:

<aTarget> is the array to be sorted.

<nStart> is the first element of the sort.  If not specified, the default starting position is one.

<nCount> is the number of elements to be sorted.  If not specified, all elements in the array beginning with the starting element are sorted.

<bOrder> is an optional code block used to determine sorting order.  If not specified, the default order is ascending.

 Returns:

ASORT() returns a reference to the <aTarget> array.

 Description:

 ASORT() is an array function that sorts all or part of an array  containing elements of a single data type.  Data types that can be  sorted include character, date, logical, and numeric.

If the <bOrder> argument is not specified, the default order is ascending.  Elements with low values are sorted toward the top of the  array (first element), while elements with high values are sorted toward the bottom of the array (last element).

If the <bOrder> block argument is specified, it is used to determine the sorting order.  Each time the block is evaluated; two elements from the target array are passed as block parameters.  The block must return true     (.T.) if the elements are in sorted order.  This facility can be used to create a descending or dictionary order sort.  See the examples below.

When sorted, character strings are ordered in ASCII sequence; logical values are sorted with false (.F.) as the low value; date values are sorted chronologically; and numeric values are sorted by magnitude.

 Notes:

ASORT() is only guaranteed to produce sorted output (as defined by the block), not to preserve any existing natural order in the process.

Because multidimensional arrays are implemented by nesting sub-arrays within other arrays, ASORT() will not directly sort  a multidimensional array.  To sort a nested array, you must supply a code block which properly handles the sub-arrays.

 Examples:

This example creates an array of five unsorted elements, sorts the array in ascending order, then sorts the array in descending  order using a code block:

aArray := { 3, 5, 1, 2, 4 }
ASORT(aArray)
// Result: { 1, 2, 3, 4, 5 }
ASORT(aArray,,, { |x, y| x > y })
// Result: { 5, 4, 3, 2, 1 }

This example sorts an array of character strings in ascending order, independent of case.  It does this by using a code block that  converts the elements to uppercase before they are compared:

aArray := { "Fred", Kate", "ALVIN", "friend" }
ASORT(aArray,,, { |x, y| UPPER(x) < UPPER(y) })

This example sorts a nested array using the second element of each sub-array:

aKids := { {"Mary", 14}, {"Joe", 23}, {"Art", 16} }
aSortKids := ASORT(aKids,,, { |x, y| x[2] < y[2] })

Result:

{ {“Mary”, 14}, {“Art”, 16}, {“Joe”, 23} }

Last element in an array:

ATAIL() : Return the highest numbered element of an array

Syntax:

      ATAIL(<aArray>) --> Element

Arguments:

<aArray> is the array.

 Returns:

ATAIL() returns either a value or a reference to an array or object.  The array is not changed.

 Description:

ATAIL() is an array function that returns the highest numbered element  of an array.  It can be used in applications as shorthand for <aArray>[LEN(<aArray>)] when you need to obtain the last element of an      array.

Examples:

The following example creates a literal array and returns that last element of the array:

     aArray := {"a", "b", "c", "d"}
     ? ATAIL(aArray)                     // Result: d

Getting directory info:

ADIR() is a array function to obtain directory information. But it’s  a compatibility function and therefore not recommended. It is superseded by the DIRECTORY() function which returns all file information in a multidimensional array.

A sample .prg : ArrayBasics.prg 

 

ArrBass

Operator overloading

/*
Operator overloading

 Some operators overloaded by extending their functionalities.
"$" was an operator for "checking substring existence in a string" 

 For example :

 ? "A" $ "ABC" // Result: .T.
 ? "Z" $ "ABC" // Result: .F.

 Now, this operator can be used for arrays and hashs too, not only strings.

 See examples below.

 "=>" was a preprocessor operator with meaning "translate to : ...".

Now, this operator can be used as a <key> - <value> separator in Hashs
for define and / or assign <key> - <value> to Hashs.
See examples below.

 "[ ]" was Array element indicator (Special)
 "{ }" was Literal array and code block delimiters (Special)

Now, this indicators can be used for hashs too. 
See examples below.

"+=" is self-increment operator that can be used both numeric 
and string values.

 Such as :

 cTest := "This"
 cTest += " is" 
 ? cTest // This is

 nTest := 3
 nTest += 10
 ? nTest // 13

 Now, this operator can be used for adding elements to an existing hash;
 ( but no for arrays ! ).
 Note : Extended functionalities of $ and += operators depends xHB lib.
        So need this usages to xHB lib and xHB.ch.

 See examples below.

*/
#include "xhb.ch"
PROCEDURE Main()

 CLS

 aFruits := { "apple", "appricot", "cherry", "melon", "pear", "mulberry" }

 ? "aFruits", IF( "pear" $ aFruits, '', 'not ' ) + "contain pear"
 ? "aFruits", IF( "grapes" $ aFruits, '', 'not ' ) +"contain grapes"

 aComplex := ARRAY( 10 )
AEVAL( aComplex, { | x1, i1 | aComplex[ i1 ] := i1 } )

 aComplex[ 5 ] := DATE()
 aComplex[ 7 ] := .F.

 ?
 ? "aComplex", IF( 3 $ aComplex, '', 'not ' ) + "contain 3"
 ? "aComplex", IF( 13 $ aComplex, '', 'not ' ) + "contain 13"
 ? "aComplex", IF( .T. $ aComplex, '', 'not ' ) + "contain .T."
 ? "aComplex", IF( .F. $ aComplex, '', 'not ' ) + "contain .F."
hEmpty := { => }
 ?
 ? "hEmpty is a", VALTYPE( hEmpty ), "type variable have",;
 STR( LEN( hEmpty ), 1 ), "element and it's",;
 IF( EMPTY( hEmpty ), '', 'not' ), "Empty"
hCountries := { 'Argentina' => "Buenos Aires" }
 hCountries += { 'Brasil' => "Brasilia" }
 hCountries += { 'Chile' => "Santiago" }
 hCountries += { 'Mexico' => "Mexico City" }

 ?
 ? "hCountries is a", VALTYPE( hCountries ), "type variable have",;
 STR( LEN( hCountries ), 1 ), "elements and and it's",;
 IF( EMPTY( hCountries ), '', 'not' ), "Empty"
cCountry := NIL
 FOR EACH cCountry IN hCountries
 ? cCountry:__ENUMKEY(), "=>", cCountry:__ENUMVALUE()
 NEXT 

 hDays := { 'Days' => { "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun" } }

 ?
 ? "hDays", IF( 'Days' $ hDays, '', 'not ' ) + "contain Days" 
 ? "hDays", IF( "Mon" $ hDays, '', 'not ' ) + "contain Mon" 
 ? "hDays['Days']", IF( "Fri" $ hDays["Days"], '', 'not ' ) + "contain Fri"
hLanguages := { "EN" => "English" } +; 
 { "DE" => "Deutsche" } +; 
 { "ES" => "Español" } +; 
 { "FR" => "Français" } +; 
 { "IT" => "Italiano" } +; 
 { "PL" => "Polkski" } +; 
 { "PT" => "Português" } +; 
 { "RU" => "Russkî" } +; 
 { "TR" => "Türkçe" }

 ?
 ? "hLanguages is a", VALTYPE( hLanguages ), "type variable have",;
 STR( LEN( hLanguages ), 1 ), "elements and and it's",;
 IF( EMPTY( hLanguages ), '', 'not' ), "Empty"
cLanguage := NIL 
 FOR EACH cLanguage IN hLanguages
 ? cLanguage:__ENUMKEY(), "=>", cLanguage:__ENUMVALUE()
 NEXT 

 @ MAXROW(), 0 
 WAIT "EOF OprOLoad.prg"
RETURN // OprOLoad.Prg.Main()
OprOLoad

Harbour New Data types

Data type & Syntax extensions in Harbour

In addition to Clipper’s scalar ( Character, Number, Date, Logical, MEMO, Nil ) and complex ( array, CodeBlock )  data types; Harbour has extended data types: pointer as scalar and object and hach as complex type.

For standard data types please refer here and/or here.

In database files (tables) data types of fields are predefined in structure of table.

For extended field types please refer here.

For data items other than fields (such as variables and manifest constants); in general, type of data  determined automatically by system, when assigning a value. The first basic way of this, is assigning a “literal” value.

For a working sample about constants please refer here.

cString := "This is a string" // A character string enclosed by a string delimiter
nNumber := 123.45 // A numeric value combined digits, decimal point and a sign ( + / - )
lTrue   := .T. // A T (tYy) or F (fNn) letter enclosed by two periods (.)
aArray  := {} // Arrays can be assigned literally by enclosed with curly brace

In addition to this basic literal value notations, Harbour has also extended notations:

– Data Types determined by special prefixs

— 0x… : Hexadecimal constant

  nNumber := 0x0A  // 0x prefix implies the string as Hexadecimal String  
                   // and type of resulting value become as Numeric (N) 
  ? nNumber, VALTYPE( nNumber ) // 10 N

— 0d… date constant

    dDate_1 := 0d20121225  // 0d prefix implies the string a date string 
                           // ( instead of using CTOD() )
                           // and type of resulting value become as Date (D) 
    ? dDate_1, VALTYPE( dDate_1 ) // 25.12.2012 D

– Special literal string formats

— d”…” : Date constant

dDate_2 := d"2012-12-26" ? dDate_2, VALTYPE( dDate_2 ) // 26.12.2012 D

— t”…” : Time constant

tTime_1 := dDate_2 + t”01:31:06″

? tTime_1, VALTYPE( tTime_1 ) // 26.12.2012 01:31:06.000 T

— e”…” : Escape sequences

Escape sequences are used to define certain special characters within string literals.

( Prefix by “\” escape sequence codes within that string )

The following escape sequences are available in C and C++ language :

Escape
sequence Description            Representation

   '     single quote          byte 0x27
   "     double quote          byte 0x22
   ?     question mark         byte 0x3f
         backslash             byte 0x5c

         null character        byte 0x00
   a     audible bell          byte 0x07
   b     backspace             byte 0x08
   f     form feed - new page  byte 0x0c
   n     line feed - new line  byte 0x0a
   r     carriage return       byte 0x0d
   t     horizontal tab        byte 0x09
   v     vertical tab          byte 0x0b

   nnn   arbitrary octal value byte nnn
   xnn   arbitrary hexadecimal value byte nn

   unnnn arbitrary Unicode value.
          May result in several characters. code point U+nnnn
   Unnnnnnnn arbitrary Unicode value.
           May result in several characters. code point U+nnnnnnnn

Note that all sequences not available in Harbour.

For the new complex data type Hash, there is a literally assigning way :

hHash := { => }    // => sign indicates the hash

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

PROCEDURE Main()
SET CENT ON
SET DATE GERM
CLS

* Data Types determined by special prefixs

** 0x... : Hexadecimal constant

nNumber := 0x0A // 0x prefix implies the string as Hexadecimal String 
// and type of resulting value become as Numeric(D)
? nNumber, VALTYPE( nNumber ) // 10 N
** 0d... date constant 

 dDate_1 := 0d20121225 // 0d prefix implies the string a date string 
                       // ( instead of using CTOD() )
                       // and type of resulting value become as Date (D) 

? dDate_1, VALTYPE( dDate_1 ) // 25.12.2012 D
* Special literal string formats
** d"..." : Date constant
dDate_2 := d"2012-12-26"
? dDate_2, VALTYPE( dDate_2 ) // 26.12.2012 D 

** t"..." : Time constant
tTime_1 := dDate_2 + t"01:31:06"
? tTime_1, VALTYPE( tTime_1 ) // 26.12.2012 01:31:06.000 T

** e"..." : Escape sequences 

? e"This is\na string\nformatted by\nEscape sequences \x21

/* The result : 
This is
a string
formatted by
Escape sequences !
*/
@ MAXROW(), 0 WAIT "EOF DTS_Exts.prg" 
RETURN // DTS_Exts.Main() 

*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DTS_Exts

Try these new 5.01 language constructs

Try these new 5.01 language constructs

The secrets of array handling, part 1.

The secrets of array handling Part – 1