使用“in”和“and”操作在ocaml中传递多个语句

时间:2015-04-25 13:41:32

标签: ocaml ocamlbuild

我想将此C ++代码转换为ocaml,但我收到语法错误

C ++代码

int** matrix(int n,int **a,int**b)
{
t=n/2;
a11=new int*[t];
for(i=0;i<t;i++)
    a11[i]=new int [t];
for(i=0;i<t;i++)
    for(j=0;j<t;j++)
        a11[i][j]=a[i][j];

a12=new int*[t];
for(i=0;i<t;i++)
    a12[i]=new int [t];
for(i=0;i<t;i++)
    for(j=0;j<t;j++)
        a12[i][j]=a[i][j+t];

a21=new int*[t];
for(i=0;i<t;i++)
    a21[i]=new int [t];
for(i=0;i<t;i++)
    for(j=0;j<t;j++)
        a21[i][j]=a[i+t][j];
}

Ocaml代码

let matrix n x y =
let t = n/2 in
        let a11 = Array.make_matrix t t 0 in
        for i = 0 to t-1 do
            for j = 0 to t-1 do
            a11.(i).(j) <- x.(i).(j)
            done
        done            
        and
        a12 = Array.make_matrix t t 0 in
        for i = 0 to t-1 do
            for j = 0 to t-1 do
            a12.(i).(j) <- x.(i).(j+t)
            done
        done        
        and
        a21 = Array.make_matrix t t 0 in
        for i = 0 to t-1 do
            for j = 0 to t-1 do
            a21.(i).(j) <- x.(i+t).(j)
            done
        done
;;

问题是t的值没有在a12和a21数组中传递,而且它是无限制的。

2 个答案:

答案 0 :(得分:2)

and的{​​{1}}无法出现在let的正文中。相反,使用多个let:

let

答案 1 :(得分:0)

为了澄清,以下问题与原始代码相同:

using System;
using System.Collections.Generic;

namespace SplitList
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<int> { 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1 };

            List<List<int>> splitSequences = new List<List<int>>();

            List<int> curSequence = new List<int>();

            foreach (var item in list)
            {
                if (item == 1) {
                    curSequence.Add(item);
                } else {
                    //Only push the current sequence onto the list of sequences if it is not empty,
                    //which could happen if multiple zeroes are encountered in a row
                    if (curSequence.Count > 0) {
                        splitSequences.Add(curSequence);
                        curSequence = new List<int>();
                    }
                }
            }
            //push any final list
            if (curSequence.Count > 0)
            {
                splitSequences.Add(curSequence);
            }

            foreach (var seq in splitSequences) {
                String line = String.Join(",", seq);
                Console.WriteLine(line);
            }

            Console.WriteLine("");
            Console.WriteLine("Press any key to exit");
            var discard = Console.ReadKey();
        }
    }
}

由于struct S{ unsigned char bit : 4; }; 定义了一个表达式,这相当于写# let x = 4 in () and y = 7 in ();; Error: Syntax error ,这实际上不是合法的OCaml。

正确使用let如下所示:

() and ()

有几个let ... and但只有一个 # let x = 4 and y = 7 in ();; Warning 26: unused variable x. Warning 26: unused variable y. - : unit = ()