用一定数量的元素定义数组类型

时间:2019-05-18 12:09:47

标签: types f#

我想创建一个数组,该数组最多可以包含三个元素。有没有办法在类型定义中做到这一点?

3 个答案:

答案 0 :(得分:6)

不,那将不再是数组。但是,您可以创建包含三个元素的元组:

let triple: int * int * int = (1, 2, 3)

元组还可以具有不同类型的元素,并且可以直接进行结构化,而不必通过模式匹配,因为它的确切形状在编译时是已知的:

let (a, b, c): int * float * string = (1, 2.7, "3")

答案 1 :(得分:3)

是的,您可以:

type Array3<'T> = private Array3 of 'T [] with
    member this.Elements = let (Array3 xs) = this in xs
    static member Create x y z = Array3 [|x;y;z|]

现在可以确保每次看到类型为Array3的值时,该值都具有三个元素:

let myArray = Array3.Create 1 2 3
myArray.Elements |> printfn "%A"

您可以在此book中了解有关此技术的更多信息。

答案 2 :(得分:2)

基于@Nghia Bui和@glennsl的答案,您可以使用三个元素的元组来定义自己的if (isset($_POST['submit'])) {类型,以确保类型安全:

syntax

或者您可以使其通用:

  <?php
    $to = 'email@email.hu';
    if (isset($_POST['email'])) {
      $from = $_POST['email'];
    } else {
      exit("Provide a valid email address!");
    }
    $subject = "XXXXXXX";
    if (isset($_POST['name'])) {
      $name = $_POST['name'];
    } else {
      exit("Provide a valid name!");
    }
    $htmlContent = '
    <html>
    <body>
    <center>
        <table rules="all" style="border-color: #666;" cellpadding="10" width="40% text-align: center;">
            <tr style="background-color: #43464b; color: white;"><td><strong>name:</strong> </td></td>' . $name. '</td></tr>
        </table>
        </center>
    </body>
    </html>';
    $headers = "MIME-Version: 1.0" . "\r\n";
    $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
    $headers .= 'From: Webnév<web@web.hu>' . "\r\n";
    $headers .= 'Cc: welcome@example.com' . "\r\n";
    $headers .= 'Bcc: welcome2@example.com' . "\r\n";
    if (isset($_POST['submit'])) {
      if (mail($to,$subject,$htmlContent,$headers)) {
        header("Location: thanks.php");
      } else {
        header("Location: sorry.php");
      }
    }
    ?>