1 people like it.
Like the snippet!
intersperse last
Fold a string with one delimiter except for the last with a different delim. So basically if you have a list ["1";"2";"3"] and you want it to be ["1";",";"2";"and";"3]
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
|
open System
let intersperseLast lastDelim delim list =
let length = Seq.length list
Seq.scan (fun acc elem ->
match acc with
| (count, state) when count < length - 1 -> (count + 1, delim::elem::state)
| (count, state) when count = length -> (count + 1, elem::state)
| (count, state) -> (count + 1, lastDelim::elem::state)) (1, []) list
|> Seq.last
|> snd
|> Seq.toList
|> List.rev
let intersperseLastList lastDelim delim list =
let length = List.length list
List.foldBack(fun elem acc ->
match acc with
| (count, state) when count = 1 -> (count - 1, elem::state)
| (count, state) when count = length -> (count - 1, lastDelim::elem::state)
| (count, state) -> (count - 1, delim::elem::state)) list (length, [])
|
namespace System
val intersperseLast : lastDelim:'a -> delim:'a -> list:seq<'a> -> 'a list
Full name: Script.intersperseLast
val lastDelim : 'a
val delim : 'a
Multiple items
val list : seq<'a>
--------------------
type 'T list = List<'T>
Full name: Microsoft.FSharp.Collections.list<_>
val length : int
module Seq
from Microsoft.FSharp.Collections
val length : source:seq<'T> -> int
Full name: Microsoft.FSharp.Collections.Seq.length
val scan : folder:('State -> 'T -> 'State) -> state:'State -> source:seq<'T> -> seq<'State>
Full name: Microsoft.FSharp.Collections.Seq.scan
val acc : int * 'a list
val elem : 'a
val count : int
val state : 'a list
val last : source:seq<'T> -> 'T
Full name: Microsoft.FSharp.Collections.Seq.last
val snd : tuple:('T1 * 'T2) -> 'T2
Full name: Microsoft.FSharp.Core.Operators.snd
val toList : source:seq<'T> -> 'T list
Full name: Microsoft.FSharp.Collections.Seq.toList
Multiple items
module List
from Microsoft.FSharp.Collections
--------------------
type List<'T> =
| ( [] )
| ( :: ) of Head: 'T * Tail: 'T list
interface IEnumerable
interface IEnumerable<'T>
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 rev : list:'T list -> 'T list
Full name: Microsoft.FSharp.Collections.List.rev
val intersperseLastList : lastDelim:'a -> delim:'a -> list:'a list -> int * 'a list
Full name: Script.intersperseLastList
Multiple items
val list : 'a list
--------------------
type 'T list = List<'T>
Full name: Microsoft.FSharp.Collections.list<_>
val length : list:'T list -> int
Full name: Microsoft.FSharp.Collections.List.length
val foldBack : folder:('T -> 'State -> 'State) -> list:'T list -> state:'State -> 'State
Full name: Microsoft.FSharp.Collections.List.foldBack
More information