0 people like it.

Pack consecutive duplicates of list elements into sublists

Pack consecutive duplicates of list elements into sublists.If a list contains repeated elements they should be placed in separate sublists.

 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
//Pack consecutive duplicates of list elements into sublists.
// https://sites.google.com/site/prologsite/prolog-problems/1
let packDups l = 
       let result =  List.foldBack (
                            fun ele (flist,(mainlist:List<List<_>>)) -> 
                                    match (flist,mainlist) with
                                    |([],_)   ->  (ele::flist,mainlist) 
                                    |(h::_,_) when ele = h -> ((ele::flist),mainlist)
                                    |(_::_,s) when s.Head = List.empty  -> ([ele], [flist])
                                    |(_::_,_) -> ([ele],flist::mainlist)
                                    ) l ([], [[]] )  
       fst(result)::snd(result) 

packDups [1;1;2;2;1;1;3;3;4] 
val packDups : l:'a list -> 'a list list (requires equality)

Full name: Script.packDups
val l : 'a list (requires equality)
val result : 'a list * List<List<'a>> (requires equality)
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 foldBack : folder:('T -> 'State -> 'State) -> list:'T list -> state:'State -> 'State

Full name: Microsoft.FSharp.Collections.List.foldBack
val ele : 'a (requires equality)
val flist : 'a list (requires equality)
val mainlist : List<List<'a>> (requires equality)
val h : 'a (requires equality)
val s : List<List<'a>> (requires equality)
property List.Head: List<'a>
val empty<'T> : 'T list

Full name: Microsoft.FSharp.Collections.List.empty
val fst : tuple:('T1 * 'T2) -> 'T1

Full name: Microsoft.FSharp.Core.Operators.fst
val snd : tuple:('T1 * 'T2) -> 'T2

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

More information

Link:http://fssnip.net/87
Posted:5 years ago
Author:Naveen
Tags: list