2 people like it.

Intersperse a list

Tail recursive implementation of an intersperse function.

Implementation

1: 
2: 
3: 
4: 
5: 
6: 
7: 
module List =
    /// The intersperse function takes an element and a list and
    /// 'intersperses' that element between the elements of the list.
    let intersperse sep ls =
        List.foldBack (fun x -> function
            | [] -> [x]
            | xs -> x::sep::xs) ls []

Example with int

1: 
List.intersperse 0 [1..10]

Example with fable-arch

1: 
2: 
3: 
model.counters
|> List.map Counter.view
|> List.intersperse (hr [])
Multiple items
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member GetSlice : startIndex:int option * endIndex:int option -> 'T list
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val intersperse : sep:'a -> ls:'a list -> 'a list

Full name: Script.List.intersperse


 The intersperse function takes an element and a list and
 'intersperses' that element between the elements of the list.
val sep : 'a
val ls : 'a list
val foldBack : folder:('T -> 'State -> 'State) -> list:'T list -> state:'State -> 'State

Full name: Microsoft.FSharp.Collections.List.foldBack
val x : 'a
val xs : 'a list
Multiple items
module List

from Script

--------------------
module List

from Microsoft.FSharp.Collections

--------------------
type List<'T> =
  | ( [] )
  | ( :: ) of Head: 'T * Tail: 'T list
  interface IEnumerable
  interface IEnumerable<'T>
  member GetSlice : startIndex:int option * endIndex:int option -> 'T list
  member Head : 'T
  member IsEmpty : bool
  member Item : index:int -> 'T with get
  member Length : int
  member Tail : 'T list
  static member Cons : head:'T * tail:'T list -> 'T list
  static member Empty : 'T list

Full name: Microsoft.FSharp.Collections.List<_>
val map : mapping:('T -> 'U) -> list:'T list -> 'U list

Full name: Microsoft.FSharp.Collections.List.map

More information

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