Using Top.Fold to count fields of a record

From Impredicative Wiki
(Difference between revisions)
Jump to: navigation, search
m (Fixed missing pre tag)
(A simpler way)
 

Latest revision as of 10:15, 8 December 2010

This code example shows a use of Top.Fold to count the fields of a type level record.

con rr :: {Type} = [One = int, Two = string, Three = bool, Four = list float] 

val q : int = @@fold [fn (rx :: {Type}) => (int)]
                (fn [nm :: Name] [t :: Type] [r :: {Type}] [[nm] ~ r] acc => 1 + acc)
                (0) [rr] (_ : folder rr)


fun main () = return <xml>
  <head>
    <title>Count fields of a record type</title>
  </head>
  <body>
    <h1>Count fields of a record type</h1>
    <p>
      We can use fold to count the fields in a type level record.
    </p>
    <p>
      Here is the value of q: {[q]}
    </p>
  </body>
</xml>

[edit] A simpler way of writing it

con rr = [One = int, Two = string, Three = bool, Four = list float] 

val q = @@fold [fn _ => int]
          (fn [nm ::_] [t ::_] [r ::_] [[nm] ~ r] acc => 1 + acc)
          0 [rr] _
Personal tools