Functional Programming Principles in Scala

함수 언어의 한 종류인 스칼라에 대해서 소개해 드립니다.

자세한 스칼라 언어소개는 아래의 위키를 참조하시기 바랍니다.

https://ko.wikipedia.org/wiki/%EC%8A%A4%EC%B9%BC%EB%9D%BC_(%ED%94%84%EB%A1%9C%EA%B7%B8%EB%9E%98%EB%B0%8D_%EC%96%B8%EC%96%B4)

 

아래 링크는 스칼라 언어 창시자인 마틴 오더스키(Martin Odersky) 교수님께서 강의를 진행한 교세라 링크입니다.

https://www.coursera.org/course/progfun

교세라 강의는 스칼라 개발 환경 셋팅부터 7주에 걸쳐 스칼라 강의를 진행하며 Lecture Note, Video 강의를 제공합니다.

Tools Setup


 

 

 

In order to work on the programming assignments, you need to have the following tools installed on your machine:

  • JDK, the Java Development Kit, version 1.7 or 1.8
  • Sbt, a build tool for Scala, version 0.13.x
  • The Scala IDE for Eclipse (or another IDE of your choice)

Please follow the instructions on this page carefully.

Installing the JDK

Linux

  • Ubuntu, Debian: To install the JDK using apt-get, execute the following command in a terminal sudo apt-get install openjdk-7-jdk
  • Fedora, Oracle, Red Had: To install the JDK using yum, execute the following command in a terminal su -c "yum install java-1.7.0-openjdk-devel"
  • Manual Installation: To install the JDK manually on a Linux system, follow these steps:
    1. Download the .tar.gz archive from http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html
    2. Unpack the downloaded archive to a directory of your choice
    3. Add the bin/ directory of the extracted JDK to the PATH environment variable. Open the file ~/.bashrc in an editor (create it if it doesn't exist) and add the following line export PATH=/PATH/TO/YOUR/jdk1.7.0-VERSION/bin:$PATH

Verify your setup: Open a new terminal (to apply the changed .bashrc in case you did the manual installation) and type java -version. If you have problems installing the JDK, ask for help on the forums.

Mac OS X

Mac OS X either comes with a pre-installed JDK, or installs it automatically.

To verify your JDK installation, open the Terminal application in /Applications/Utilities/ and type java -version. If the JDK is not yet installed, the system will ask you if you would like to download and install it.

Windows

To verify the JDK installation, open the Command Prompt and type java -version. If you have problems installing the JDK, ask for help on the forums.

Installing sbtDonwload sbt for your platform here. Follow the instructions that page to get it running.

This course requires sbt version 0.13.x. If you have previously installed sbt 0.12.x, you need to uninstall it and install a newer version. sbt 0.13.x can be used for projects and other courses requiring sbt 0.12.x, but not the other way around. If in doubt, you can check your currently installed sbt like this: in an arbitrary directory that is not a programming assignment or otherwise an sbt project, run:

$ sbt --version

You should see something like this:

sbt launcher version 0.13.0

If the sbt command is not found, or if you get a non-0.13.x version, you need to install sbt 0.13.x.

Installing the Scala IDE for Eclipse with the Scala Worksheet (Linux / Mac OS X / Windows)

You can download the Scala IDE for eclipse with the Scala Worksheet pre-installed from the following URL:

http://scala-ide.org/download/sdk.html (Make sure to download the IDE for Scala version 2.11.x!)

After downloading the archive for your operating system, simply unpack it and start eclipse. Eclipse requires you to select a workspace on startup. We recommend you create one workspace directory for this class and use it for all assignments.

Hello World: Scala IDE and the Scala Worksheet

To familiarize yourself with the Scala IDE, create a small "Hello World" project in eclipse:

  1. Go to "File" - "New" - "Other..." and select "Scala Project" from the folder "Scala Wizards"
  2. Chose a project name and select "Finish" 
  3. Select "File" - "New" - "Scala Object" to create a new object
  4. Enter Hello as the name for the object and put greeter as the package name above 
  5. Change the source code to the one given below [1]
  6. Save the file and select "Run" - "Run" from the menu. Chose to run as "Scala Application" 

You should see a the hello world output in the Eclipse console.

[1] Source code

package greeter
object Hello extends App {
  println("Hello, World!")
}

Creating a Scala Worksheet

Creating a Scala Worksheet is very easy:

  1. Right-click on the package greeter in the hello world project that you just created
  2. Select "New" - "Scala Worksheet"
  3. Choose a name for your worksheet (different than Hello or the name you chose for the "Scala Object" before)

Now you can type some Scala code into the worksheet. Every time you save the file, the content of the worksheet will be evaluated. Copy the following code into the object of your worksheet:

  val x = 1                                       //> x  : Int = 1
  def increase(i: Int) = i + 1                    //> increase: (i: Int)Int
  increase(x)                                     //> res0: Int = 2

IntelliJ (optional alternative IDE)

If you want to use the IntelliJ IDE instead of Eclipse, some guidance is provided through the IntelliJ tutorial page and the IntelliJ getting started video.

 

 

Sbt Tutorial

We use sbt for building, testing, running and submitting assignments. This tutorial explains all sbt commands that you will use during our class. The Tools Setup page explains how to install sbt.

Starting up sbt

In order to start sbt, open a terminal ("Command Prompt" in Windows) and navigate to the directory of the assignment you are working on. Typing sbt will open the sbt command prompt.

shell$ cd /path/to/progfun-project-directory                        # This is the shell of the operating system
shell$ sbt
> _                                                                 # This is the sbt shell

Running the Scala Interpreter

You can start the Scala interpreter inside sbt using the console task. The interpreter (also called REPL, for "read-eval-print loop") is useful for trying out snippets of Scala code. Note that the interpreter can only be started if there are no compilation errors in your code.

In order to quit the interpreter and get back to sbt, type ctrl-d.

> console
[info] Starting scala interpreter...
Welcome to Scala version 2.11.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_04-ea).
Type in expressions to have them evaluated.
Type :help for more information.

scala> println("Oh, hai!")                                          # This is the Scala REPL, type some Scala code
Oh, hai!

scala> val l = List(1, 2, 3)
l: List[Int] = List(1, 2, 3)

scala> val squares = l.map(x => x * x)
squares: List[Int] = List(1, 4, 9)

scala>                                                              # Type [ctrl-d] to exit the Scala REPL
[success] Total time: 20 s, completed Mar 21, 2013 11:02:31 AM
>                                                                   # We're back to the sbt shell

Compiling your Code

The compile task will compile the source code of the assignment which is located in the directory src/main/scala.

> compile
[info] Compiling 4 Scala sources to /Users/aleksandar/example/target/scala-2.11/classes...
[success] Total time: 1 s, completed Mar 21, 2013 11:04:46 PM
> 

If the source code contains errors, the error messages from the compiler will be displayed.

Testing your Code

The directory src/test/scala contains unit tests for the project. In order to run these tests in sbt, you can use the test command.

> test
[info] ListsSuite:
[info] - one plus one is two
[info] - sum of a few numbers *** FAILED ***
[info]   3 did not equal 2 (ListsSuite.scala:23)
[info] - max of a few numbers
[error] Failed: : Total 3, Failed 1, Errors 0, Passed 2, Skipped 0
[error] Failed tests:
[error]   example.ListsSuite
[error] {file:/Users/luc/example/}assignment/test:test: Tests unsuccessful
[error] Total time: 5 s, completed Aug 10, 2012 10:19:53 PM
> 

Running your Code

If your project has an object with a main method (or an object extending the trait App), then you can run the code in sbt easily by typing run. In case sbt finds multiple main methods, it will ask you which one you'd like to execute.

> run
Multiple main classes detected, select one to run:

 [1] example.Lists
 [2] example.M2

Enter number: 1

[info] Running example.Lists 
main method!
[success] Total time: 33 s, completed Aug 10, 2012 10:25:06 PM
>

Submitting your Solution to Coursera

The sbt task submit allows you to submit your solution for the assignment. It will pack your source code into a .jar file and upload it to the coursera servers. Note that the code can only be submitted if there are no compilation errors.

The submit tasks takes two arguments: your Coursera e-mail address and the submission password. NOTE: the submission password is not your login password. Instead, it's a special password generated by coursera. It is available on theAssignments page.

> submit e-mail@university.org suBmISsioNPasSwoRd
[info] Packaging /Users/luc/example/target/scala-2.11/progfun-example_2.11-1.0.0-sources.jar ...
[info] Done packaging.
[info] Compiling 1 Scala source to /Users/luc/example/target/scala-2.11/classes...
[info] Connecting to coursera. Obtaining challenge...
[info] Computing challenge response...
[info] Submitting solution...
[success] Your code was successfully submitted: Your submission has been accepted and will be graded shortly.
[success] Total time: 6 s, completed Aug 10, 2012 10:35:53 PM
>

 

Eclipse Tutorial

We recommend using the Scala IDE for Eclipse to work on the programming assignments for this course. You are of course free to use any text editor or IDE - however we are not able to provide tutorials or support for other tools.

The Tools Setup page explains how to install the Scala IDE for eclipse.

Creating the Eclipse project from sbt

First, you need to create the Eclipse from sbt, using the eclipse command:

$ sbt
> eclipse
...

Opening the Project in Eclipse

Once the Eclipse project has been created from sbt, you can import it in Eclipse. Follow these steps to work on the project using the Scala IDE:

  1. Start up Eclipse
  2. Select "File" - "Import" from the menu
  3. In the folder "General", select the item "Existing Projects into Workspace" and click "Next >"
  4. In the textfield "Select root directory:" select the directory where you unpacked the downloaded handout archive
  5. Click "Finish".

Working with Eclipse

To learn how to use the Scala IDE, we recommend you to watch the official tutorial video which is available here: http://scala-ide.org/docs/current-user-doc/gettingstarted/index.html.

This website also contains a lot more useful information and handy tricks that make working with eclipse more efficient.

Running Tests inside Eclipse

You can easily execute the test suites directly inside eclipse. Simply navigate to source file of the test suite in src/test/scala, right-click on it and select "Run As" - "JUnit Test".

The JUnit window will display the result of each individual test.


 

반응형
블로그 이미지

조이풀 라이프

Lift is short, enjoy the life

,