Domanda

I'm tring to do a function on SML that invert the first list and then concatenate with the second list (someting like: list1 = [5,3,1] and list 2 = [ 6 7 8], then inv(list1,list2) = [ 1,3,5,6,7,8].) Here's the code:

fun inv (nil,nil) = []
|inv (ha::ta,hb::tb) = 
 if ha = [] then ta::(hb::tb)
 else  ha::inv(ta,hb::tb);

It returns this:

Error: types of if branches do not agree [circularity] then branch: ''Z list list list else branch: ''Z list list in expression:

if ha = nil then ta :: hb :: tb else ha :: inv (ta, :: )

Can anyone help me with this please?

È stato utile?

Soluzione

fun inv ([], b) = b
 |  inv (h::t, b) = inv(t, h::b)

Note that you don't need pattern matching on the second list. This is a canonical example of a tail recursive function; it is the way to reverse a list with constant stack space. You error was using cons (::) where the first argument had type 'a list.

Altri suggerimenti

Since you're working with lists, if ha =[], then there is no other term remaining in list1.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top