7 people like it.

Chunk String by Size into List of String Chunks

Easy way to chunk string into equal segments. Returns a list of string chunks (as opposed to an array or seq of chunks).

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
let chunkStr size str =
    let rec loop (s:string) accum =
        let branch = size < s.Length
        match branch with
        | true  -> loop (s.[size..]) (s.[0..size-1]::accum)
        | false -> s::accum
    (loop str []) |> List.rev

//example
"A man, a plan, a canal: Panama." |> chunkStr 3
//result: ["A m"; "an,"; " a "; "pla"; "n, "; "a c"; "ana"; "l: "; "Pan"; "ama"; "."]
val chunkStr : size:int -> str:string -> string list

Full name: Script.chunkStr
val size : int
val str : string
val loop : (string -> string list -> string list)
val s : string
Multiple items
val string : value:'T -> string

Full name: Microsoft.FSharp.Core.Operators.string

--------------------
type string = System.String

Full name: Microsoft.FSharp.Core.string
val accum : string list
val branch : bool
property System.String.Length: int
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 rev : list:'T list -> 'T list

Full name: Microsoft.FSharp.Collections.List.rev
Raw view Test code New version

More information

Link:http://fssnip.net/7Vo
Posted:5 years ago
Author:LSM07
Tags: list , string