Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cyclic lists in F#

Tags:

f#

Is it just me, or does F# not cater for cyclic lists?

I looked at the FSharpList<T> class via reflector, and noticed, that neither the 'structural equals' or the length methods check for cycles. I can only guess if 2 such primitive functions does not check, that most list functions would not do this either.

If cyclic lists are not supported, why is that?

Thanks

PS: Am I even looking at the right list class?

like image 377
leppie Avatar asked Feb 18 '10 07:02

leppie


4 Answers

There are many different lists/collection types in F#.

  • F# list type. As Chris said, you cannot initialize a recursive value of this type, because the type is not lazy and not mutable (Immutability means that you have to create it at once and the fact that it's not lazy means that you can't use F# recursive values using let rec). As ssp said, you could use Reflection to hack it, but that's probably a case that we don't want to discuss.

  • Another type is seq (which is actually IEnumerable) or the LazyList type from PowerPack. These are lazy, so you can use let rec to create a cyclic value. However, (as far as I know) none of the functions working with them take cyclic lists into account - if you create a cyclic list, it simply means that you're creating an infinite list, so the result of (e.g.) map will be a potentially infinite list.

Here is an example for LazyList type:

 #r "FSharp.PowerPack.dll"

 // Valid use of value recursion
 let rec ones = LazyList.consDelayed 1 (fun () -> ones)
 Seq.take 5 l // Gives [1; 1; 1; 1; 1]

The question is what data types can you define yourself. Chris shows a mutable list and if you write operations that modify it, they will affect the entire list (if you interpret it as an infinite data structure).

You can also define a lazy (potentionally cyclic) data type and implement operations that handle cycles, so when you create a cyclic list and project it into another list, it will create cyclic list as a result (and not a potentionally infinite data structure).

The type declaration may look like this (I'm using object type, so that we can use reference equality when checking for cycles):

type CyclicListValue<'a> = 
  Nil | Cons of 'a * Lazy<CyclicList<'a>>

and CyclicList<'a>(value:CyclicListValue<'a>) = 
  member x.Value = value

The following map function handles cycles - if you give it a cyclic list, it will return a newly created list with the same cyclic structure:

let map f (cl:CyclicList<_>) =  
  // 'start' is the first element of the list (used for cycle checking)
  // 'l' is the list we're processing
  // 'lazyRes' is a function that returns the first cell of the resulting list
  //  (which is not available on the first call, but can be accessed
  //  later, because the list is constructed lazily)
  let rec mapAux start (l:CyclicList<_>) lazyRes =
    match l.Value with
    | Nil -> new CyclicList<_>(Nil)
    | Cons(v, rest) when rest.Value = start -> lazyRes()
    | Cons(v, rest) -> 
      let value = Cons(f v, lazy mapAux start rest.Value lazyRes)
      new CyclicList<_>(value)
  let rec res = mapAux cl cl (fun () -> res)
  res
like image 66
Tomas Petricek Avatar answered Nov 16 '22 05:11

Tomas Petricek


The F# list type is essentially a linked list, where each node has a 'next'. This in theory would allow you to create cycles. However, F# lists are immutable. So you could never 'make' this cycle by mutation, you would have to do it at construction time. (Since you couldn't update the last node to loop around to the front.)

You could write this to do it, however the compiler specifically prevents it:

  let rec x = 1 :: 2 :: 3 :: x;;

  let rec x = 1 :: 2 :: 3 :: x;;
  ------------------------^^

stdin(1,25): error FS0260: Recursive values cannot appear directly as a construction of the type 'List`1' within a recursive binding. This feature has been removed from the F# language. Consider using a record instead.

If you do want to create a cycle, you could do the following:

> type CustomListNode = { Value : int; mutable Next : CustomListNode option };;

type CustomListNode =
  {Value: int;
   mutable Next: CustomListNode option;}

> let head = { Value = 1; Next = None };;

val head : CustomListNode = {Value = 1;
                             Next = null;}

> let head2 = { Value = 2; Next = Some(head) } ;;

val head2 : CustomListNode = {Value = 2;
                              Next = Some {Value = 1;
                                           Next = null;};}

> head.Next <- Some(head2);;
val it : unit = ()
> head;;
val it : CustomListNode = {Value = 1;
                           Next = Some {Value = 2;
                                        Next = Some ...;};}
like image 39
Chris Smith Avatar answered Nov 16 '22 05:11

Chris Smith


The answer is same for all languages with tail-call optimization support and first-class functions (function types) support: it's so easy to emulate cyclic structures.

let rec x = seq { yield 1; yield! x};;

It's simplest way to emulate that structure by using laziness of seq. Of course you can hack list representation as described here.

like image 5
ssp Avatar answered Nov 16 '22 06:11

ssp


As was said before, your problem here is that the list type is immutable, and for a list to be cyclic you'd have to have it stick itself into its last element, so that doesn't work. You can use sequences, of course.

If you have an existing list and want to create an infinite sequence on top of it that cycles through the list's elements, here's how you could do it:

let round_robin lst =
    let rec inner_rr l =        
        seq {
            match l with
            | [] ->
                 yield! inner_rr lst            
            | h::t ->                
                 yield h                
                 yield! inner_rr t            
        }    
     if lst.IsEmpty then Seq.empty else inner_rr []


let listcycler_sequence = round_robin [1;2;3;4;5;6]
like image 1
Alexander Rautenberg Avatar answered Nov 16 '22 07:11

Alexander Rautenberg