2017-03-20 47 views
1

I'm brand new to SML/NJ and I'm trying to make a recursive function that makes a listOfLists. Ex: listOf([1,2,3,4]) will output [[1],[2],[3],[4]] . I've found a recursive merge in SML/NJ, and I'm trying to use it as kind've an outline:は、再帰的に

- fun merge(xs,nil) = xs 
= | merge(nil,ys) = ys 
= | merge(x::xs, y::ys) = 
= if (x < y) then x::merge(xs, y::ys) else y::merge(x::xs,ys); 

- fun listOf(xs) = xs 
= | listOf(x::xs) = [x]::listOf(xs); 

I'm trying to use pattern match and I'm a little confused on it. I'm pretty sure x is the head and then xs is the tail, but I could be wrong. So what I'm trying to do is use the head of the list, make it a list, and then add it to the rest of the list. But when trying to do this function, I get the error:

stdIn:15.19-15.34 Error: operator and operand don't agree [circularity] 
    operator domain: 'Z list * 'Z list list 
    operand:   'Z list * 'Z list 
    in expression: 
    (x :: nil) :: listOf xs 

This error is foreign to me because I don't have really any experience with sml/nj. How can I fix my listOf function?

答えて

0

SML/NJでリストのリストを作るためにどのようにかなり接近しています。パターンマッチングでは、xs(変数のみ)のパターンはと一致する可能性があります。です。 sで終了するということは、パターンがリストの末尾にのみ一致することを意味するものではありません。そのようにしてsを使用するのは、SMLのプログラマーの慣例に過ぎません。

このように、あなたの定義で:

fun listOf(xs) = xs 
| listOf(x::xs) = [x]::listOf(xs); 

最初の行が明確に意図されていない、変わらないすべての値を返すようにSMLに指示します。 SMLは、が2番目の行と矛盾していることを検出し、結局値を変更しようとします。です。

すべてのものと一致しないように最初の行を変更する必要があります。そのmergeの機能をテンプレートとして見ると、基本ケースに一致するものが必要です。自然基準のケースはnilです([]と書くこともできます)。 nilが果たす役割は、mergeの定義にあることに注意してください。あなたは、関数定義の最初の行にパターンをnilの代わりxsを使用している場合は、あなたの2行目は正確に何をしたい行い、意図したとおりに機能が動作します:

fun listOf(nil) = nil 
| listOf(x::xs) = [x]::listOf(xs); 
+0

ああ、それは完璧な理にかなっています。お手伝いありがとう! – XXIV

+0

私は、スタックオーバーフローが質問内の別の質問に嫌なことがあることは知っていますが、それは簡単な質問なので問題ではないと思います。リスト[[[1]、[2]、[3]、[4]]を[[1,2]、[3,4]]に作る必要があります。 'x'が最初の値で' xs'がリストの最後の値なので、リストの次のインデックスにはどうすればアクセスできますか? – XXIV

+0

インデックスをまったく使用しないと思わない場合は、代わりにパターンマッチングを使用してください。ヒント: '[x] :: [y] :: zsは、それぞれがシングルトンリストである少なくとも2つの要素を持つリストのパターンです。 –