0 people like it.

Intersperse an array

Imperative and fast implementation of an intersperse function for array. if you search for a functional implemenation you should look [here](http://www.fssnip.net/7S3/title/Intersperse-a-list).

Implementation

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
module Array =
    /// <summary>
    /// The intersperse function takes an element and an array and
    /// 'intersperses' that element between the elements of the array.
    /// </summary>
    /// <exception cref="System.ArgumentNullException"/>
    let intersperse sep (array: 'a array) =
        if isNull array then nullArg "arr"
        elif array.Length = 0 then [||]
        else
            let interspersedArray = Array.zeroCreate ((array.Length * 2) - 1)
            for i = 0 to array.Length - 1 do
                let j = i * 2
                interspersedArray.[j] <- array.[i]
                if (j < interspersedArray.Length - 1) then
                    interspersedArray.[j + 1] <- sep
            interspersedArray

Example

1: 
2: 
3: 
4: 
Array.intersperse 0 [|1..10|]

// throws a null arg exception, like any other Array module func
Array.intersperse 0 null
module Array

from Microsoft.FSharp.Collections
val intersperse : sep:'a -> array:'a array -> 'a []

Full name: Script.Array.intersperse


 <summary>
 The intersperse function takes an element and an array and
 'intersperses' that element between the elements of the array.
 </summary>
 <exception cref="System.ArgumentNullException"/>
val sep : 'a
Multiple items
val array : 'a array

--------------------
type 'T array = 'T []

Full name: Microsoft.FSharp.Core.array<_>
val isNull : value:'T -> bool (requires 'T : null)

Full name: Microsoft.FSharp.Core.Operators.isNull
val nullArg : argumentName:string -> 'T

Full name: Microsoft.FSharp.Core.Operators.nullArg
property System.Array.Length: int
val interspersedArray : 'a []
val zeroCreate : count:int -> 'T []

Full name: Microsoft.FSharp.Collections.Array.zeroCreate
val i : int
val j : int
Multiple items
module Array

from Script

--------------------
module Array

from Microsoft.FSharp.Collections
Raw view Test code New version

More information

Link:http://fssnip.net/7S4
Posted:7 years ago
Author:Tobias Burger
Tags: array , intersperse