3
fun Dbt (nil,_) =  nil
  | Dbt (x::xs,y::ys) = (x::y)::(Dbt(xs,ys))
  | Dbt (x::xs,nil) = [x]::(Dbt(xs,nil));

Is there a way of defining this function non-recursively by using higher order and or in built functions in sml??I have tried all I can but it seems I am not going anywhere.Any ideas will be appreciated thanks..

Emma
  • 323
  • 3
  • 16
  • I actually want to use this function to help me complete my definition of another higher order function which is not supposed to use functions defined by cases or recursion.In other words I want to make this an iterator in my 'foldr' function-part of homework,yes – Emma Oct 22 '13 at 11:54

1 Answers1

4

As you do not consume list but produce them, you won't be able to use the usual list-traversing operators (map, filter, fold...).

There is however one common and well-understood combinator for list production, which is

val unfold : ('a -> ('a * 'b) option) -> 'a -> 'b list

Unfortunately, this operator is not available in the basic SML library, so you may have to define it yourself.

fun Dbt (xs, ys) =
  let fun Step (nil, _) = NONE
      |   Step (x::xs, y::ys) = SOME (x::y,(xs,ys))
      |   Step (x::xs, nil) = SOME ([x], (xs,nil))
  in unfold Step (xs, ys)
gasche
  • 31,259
  • 3
  • 78
  • 100
  • i am trying to figure this out,but am kinda confused in the way the let expression is structured.What is Step really?it looks like my Dbt,can you explain a bit? – Emma Oct 22 '13 at 12:11
  • `Step` has all the useful content of your `Dbt` indeed, but it is not recursive. The idea is that it does "one step" of computation, returning what the next element of the list should be (in function of its input, which you can think of a state that is transformed during the list production). You should try to write the (recursive) combinator `unfold` from the type signature I gave, you'll be able to understand `Step` better by composing them together. – gasche Oct 22 '13 at 19:21
  • 2
    You probably don't want to declare three different functions called `Step` but instead one with three cases (using `| Step (x::xs...`). (I'd fix this, but apparently StackOverflow won't easily let me.) – sshine Oct 22 '13 at 22:28
  • Indeed, sorry, I messed up my rusty SML syntax. – gasche Oct 23 '13 at 11:33