此过程(elementSeparator)在ReasonML中给出类型错误

时间:2019-12-04 05:16:46

标签: types typeerror reason

此代码:

let initialRows = 5;
    let initialCols = 7;

    /* 
    Player 1 is P1, Player 2 is P2
    */

    type whichPlayer =
      | P1
      | P2;

    /* 
    Either Player 1 or Player 2 has won the game,
    it is a draw, or it is ongoing where either
    it is Player 1's turn or Player 2's turn
    */

    type status =
      | Win(whichPlayer)
      | Draw
      | Ongoing(whichPlayer);

    /*
    The current state of the game is represented by a list of lists of tuples: 
    containing the column number of the occupancy as the first element,
    and the occupant of the specified slot as the second element,
    and a status specification indicating which player's turn it is, or
    whether the game has ended in a win or a draw.
    */

    type state = 
      | State(list(list((int, whichPlayer))), status);

    /*
    A move is represented by an int, corresponding to
    the column number of the desired occupancy 
    */

    type move = 
      | Move(int);

let rec createEmptySpaces: int => string = num =>
    switch(num){
      | x when x > 1 => "( )" ++ createEmptySpaces(num-1)
      | 1 => "( )"
    };      

let rec elementSeparator: (list((int, whichPlayer)), int) => string = (lst, num) =>
switch(lst){
  | [(colNum, p), (colNum2, p2), ... tl] when num == 1 =>{
    let difference = colNum2 - colNum;
    if(colNum != 1){
      createEmptySpaces(colNum-1) ++
      if(p == P1){
        "(o)" ++ if(difference != 1){
                    createEmptySpaces(difference - 1)
                 }
      } else {
        "(x)" ++ if(difference != 1){
                    createEmptySpaces(difference - 1)
                 }
      } 
      ++ elementSeparator([(colNum2, p2)]@tl, num + 1)
    } else {
      if(p == P1){
        "(o)" ++ if(difference != 1){
                    createEmptySpaces(difference - 1)
                 }
      } else {
        "(x)" ++ if(difference != 1){
                    createEmptySpaces(difference - 1)
                 }
      }
      ++ elementSeparator([(colNum2, p2)]@tl, num + 1)
    }
  }

  | [] => ""
};

elementSeparator([(1, P1), (3, P2), (7, P1)], 1);
elementSeparator([(3, P2), (5, P2)], 1);
elementSeparator([(2, P1), (3, P2), (4, P1), (6, P2)], 1);

给我错误:

Error: This expression has type string but an expression was expected of type unit

用于第三个if表达式。我正在尝试创建一行 “(x)”,“(o)”和“()”。我不知道为什么将要抛出此错误,因为elementSeparator应该输出一个字符串。每次我尝试在第二个if表达式之后连接另一个字符串(通过函数,过程,表达式等)时,都会引发此错误。谁能帮我吗?

1 个答案:

答案 0 :(得分:1)

没有p if分支的

else表达式总是需要返回类型unit的值(因为如果if条件不能解析的话,这就是表达式的类型到true)。

可以通过添加一个返回空字符串else的{​​{1}}分支来解决此问题,或者只是为了简便起见使用三元运算符:

""