Introducción a F # en Visual Studio para MacGet started with F# in Visual Studio for Mac
F # y las herramientas de Visual F# se admiten en el IDE de Visual Studio para Mac.F# and the Visual F# tooling are supported in the Visual Studio for Mac IDE. Asegúrese de que ha instalado Visual Studio para Mac.Ensure that you have Visual Studio for Mac installed.
Creación de una aplicación de consolaCreating a console application
Uno de los proyectos más básicos de Visual Studio para Mac es la aplicación de consola.One of the most basic projects in Visual Studio for Mac is the Console Application. Aquí se muestra cómo hacerlo.Here's how to do it. Una vez que Visual Studio para Mac está abierto:Once Visual Studio for Mac is open:
En el menú archivo , elija nueva solución.On the File menu, point to New Solution.
En el cuadro de diálogo nuevo proyecto, hay dos plantillas diferentes para la aplicación de consola.In the New Project dialog, there are 2 different templates for Console Application. Hay una en otras > .NET que tiene como destino el .NET Framework.There is one under Other -> .NET which targets the .NET Framework. La otra plantilla está en .NET Core-> aplicación que tiene como destino .NET Core.The other template is under .NET Core -> App which targets .NET Core. Cualquier plantilla debe funcionar para este artículo.Either template should work for the purpose of this article.
En aplicación de consola, cambie C# a F # si es necesario.Under console app, change C# to F# if needed. Elija el botón siguiente para avanzar.Choose the Next button to move forward!
Asigne un nombre al proyecto y elija las opciones que quiera para la aplicación.Give your project a name, and choose the options you want for the app. Fíjese en el panel de vista previa en el lateral de la pantalla que mostrará la estructura de directorios que se creará en función de las opciones seleccionadas.Notice, the preview pane to the side of the screen that will show the directory structure that will be created based on the options selected.
Haga clic en Crear.Click Create. Ahora debería ver un proyecto de F # en el Explorador de soluciones.You should now see an F# project in the Solution Explorer.
Escritura del códigoWriting your code
Vamos a empezar por escribir código primero.Let's get started by writing some code first. Asegúrese de que el Program.fs
archivo está abierto y, a continuación, reemplace el contenido por lo siguiente:Make sure that the Program.fs
file is open, and then replace its contents with the following:
module HelloSquare
let square x = x * x
[<EntryPoint>]
let main argv =
printfn "%d squared is: %d!" 12 (square 12)
0 // Return an integer exit code
En el ejemplo de código anterior, se ha definido una función square
que toma una entrada denominada x
y la multiplica por sí misma.In the previous code sample, a function square
has been defined which takes an input named x
and multiplies it by itself. Dado que F # usa la inferencia de tipos, x
no es necesario especificar el tipo de.Because F# uses Type Inference, the type of x
doesn't need to be specified. El compilador de F # entiende los tipos en los que la multiplicación es válida y asignará un tipo a x
basándose en cómo square
se llama a.The F# compiler understands the types where multiplication is valid, and will assign a type to x
based on how square
is called. Si mantiene el puntero sobre square
, debería ver lo siguiente:If you hover over square
, you should see the following:
val square: x:int -> int
Esto es lo que se conoce como la firma de tipo de la función.This is what is known as the function's type signature. Se puede leer de la siguiente manera: "Square es una función que toma un entero denominado x y genera un entero".It can be read like this: "Square is a function which takes an integer named x and produces an integer". Tenga en cuenta que el compilador dio square
el int
tipo por ahora: esto se debe a que la multiplicación no es genérica en todos los tipos, sino que es genérica en un conjunto cerrado de tipos.Note that the compiler gave square
the int
type for now - this is because multiplication is not generic across all types, but rather is generic across a closed set of types. El compilador de F # eligió int
en este punto, pero ajustará la firma del tipo si llama square
a con otro tipo de entrada, como float
.The F# compiler picked int
at this point, but it will adjust the type signature if you call square
with a different input type, such as a float
.
Otra función, main
, se define, que se decora con el EntryPoint
atributo para indicar al compilador de F # que la ejecución del programa debe comenzar allí.Another function, main
, is defined, which is decorated with the EntryPoint
attribute to tell the F# compiler that program execution should start there. Sigue la misma Convención que otros lenguajes de programación de estilo C, donde se pueden pasar argumentos de línea de comandos a esta función y se devuelve un código entero (normalmente 0
).It follows the same convention as other C-style programming languages, where command-line arguments can be passed to this function, and an integer code is returned (typically 0
).
En esta función se llama a la square
función con un argumento de 12
.It is in this function that we call the square
function with an argument of 12
. A continuación, el compilador de F # asigna el tipo de square
a int -> int
(es decir, una función que toma int
y produce int
).The F# compiler then assigns the type of square
to be int -> int
(that is, a function which takes an int
and produces an int
). La llamada a printfn
es una función de impresión con formato que usa una cadena de formato, similar a los lenguajes de programación de estilo C, los parámetros que se corresponden con los especificados en la cadena de formato y, a continuación, imprime el resultado y una nueva línea.The call to printfn
is a formatted printing function which uses a format string, similar to C-style programming languages, parameters which correspond to those specified in the format string, and then prints the result and a new line.
Ejecución de códigoRunning your code
Puede ejecutar el código y ver los resultados haciendo clic en Ejecutar en el menú de nivel superior y, a continuación, iniciar sin depurar.You can run the code and see results by clicking on Run from the top level menu and then Start Without Debugging. Así se ejecutará el programa sin depurar y podrá ver los resultados.This will run the program without debugging and allows you to see the results.
Ahora debería ver lo siguiente impreso en la ventana de la consola que Visual Studio para Mac emerge:You should now see the following printed to the console window that Visual Studio for Mac popped up:
12 squared is 144!
Enhorabuena.Congratulations! Ha creado su primer proyecto de F # en Visual Studio para Mac, ha escrito una función de F # y ha impreso los resultados de una llamada a esa función, y ejecuta el proyecto para ver algunos resultados.You've created your first F# project in Visual Studio for Mac, written an F# function printed the results of calling that function, and run the project to see some results.
Usar F# interactivoUsing F# Interactive
Una de las mejores características de las herramientas de Visual F# en Visual Studio para Mac es la ventana de F# interactivo.One of the best features of the Visual F# tooling in Visual Studio for Mac is the F# Interactive Window. Permite enviar código a un proceso en el que se puede llamar a ese código y ver el resultado de forma interactiva.It allows you to send code over to a process where you can call that code and see the result interactively.
Para empezar a usarlo, resalte la square
función definida en el código.To begin using it, highlight the square
function defined in your code. A continuación, haga clic en Editar en el menú de nivel superior.Next, click on Edit from the top level menu. A continuación, seleccione Enviar selección a F# interactivo.Next select Send selection to F# Interactive. Esto ejecuta el código en la ventana F# interactivo.This executes the code in the F# Interactive Window. Como alternativa, puede hacer clic con el botón derecho en la selección y elegir Enviar selección a F# interactivo.Alternatively, you can right click on the selection and choose Send selection to F# Interactive. Debería ver que la ventana de F# interactivo aparece con lo siguiente en ella:You should see the F# Interactive Window appear with the following in it:
>
val square : x:int -> int
>
Esto muestra la misma firma de función para la square
función, que vio anteriormente al mantener el mouse sobre la función.This shows the same function signature for the square
function, which you saw earlier when you hovered over the function. Dado square
que ahora se define en el proceso de F# interactivo, puede llamarlo con valores diferentes:Because square
is now defined in the F# Interactive process, you can call it with different values:
> square 12;;
val it : int = 144
>square 13;;
val it : int = 169
De esta forma, se ejecuta la función, se enlaza el resultado a un nuevo nombre it
y se muestra el tipo y el valor de it
.This executes the function, binds the result to a new name it
, and displays the type and value of it
. Tenga en cuenta que debe terminar cada línea con ;;
.Note that you must terminate each line with ;;
. Así es como F# interactivo sabe cuándo finaliza la llamada de función.This is how F# Interactive knows when your function call is finished. También puede definir nuevas funciones en F# interactivo:You can also define new functions in F# Interactive:
> let isOdd x = x % 2 <> 0;;
val isOdd : x:int -> bool
> isOdd 12;;
val it : bool = false
Lo anterior define una nueva función, isOdd
, que toma int
y comprueba si es impar.The above defines a new function, isOdd
, which takes an int
and checks to see if it's odd! Puede llamar a esta función para ver lo que devuelve con diferentes entradas.You can call this function to see what it returns with different inputs. Puede llamar a funciones dentro de las llamadas de función:You can call functions within function calls:
> isOdd (square 15);;
val it : bool = true
También puede usar el operador de canalización directa para canalizar el valor en las dos funciones:You can also use the pipe-forward operator to pipeline the value into the two functions:
> 15 |> square |> isOdd;;
val it : bool = true
El operador de canalización hacia delante, y más, se trata en los tutoriales posteriores.The pipe-forward operator, and more, are covered in later tutorials.
Esto solo es un vistazo a lo que puede hacer con F# interactivo.This is only a glimpse into what you can do with F# Interactive. Para obtener más información, consulte programación interactiva con F #.To learn more, check out Interactive Programming with F#.
Pasos siguientesNext steps
Si todavía no lo ha hecho, consulte el paseo por f #, que trata algunas de las características principales del lenguaje f #.If you haven't already, check out the Tour of F#, which covers some of the core features of the F# language. Le proporcionará una visión general de algunas de las funcionalidades de F # y proporcionará ejemplos de código que puede copiar en Visual Studio para Mac y ejecutar.It will give you an overview of some of the capabilities of F#, and provide ample code samples that you can copy into Visual Studio for Mac and run. También hay algunos excelentes recursos externos que puede usar, que se muestran en la Guía de F #.There are also some great external resources you can use, showcased in the F# Guide.