Difference between revisions of "FP Laboratory 2"

From Marek Běhálek Wiki
Jump to navigation Jump to search
Line 20: Line 20:
 
odd 3
 
odd 3
 
</syntaxhighlight>
 
</syntaxhighlight>
# At presentations, we have spoken about some basic types: <code> Int, Double, Bool, Char<code>. For each of previous expressions assign them the most appropriate of these basic data types. You can verify your guess by using <code>::</code>. For example, for first
+
# At presentations, we have spoken about some basic types: <code> Int, Double, Bool, Char</code>. For each of previous expressions assign them the most appropriate of these basic data types. You can verify your guess by using <code>::</code>. For example, for the first expression, lets assume it is <code>Int</code>. We can cast the result to integer and get following result.
 +
<syntaxhighlight lang="Haskell" class="myDark" >
 +
Prelude> :type (5 + 8) :: Int
 +
(5 + 8) :: Int :: Int
 +
</syntaxhighlight>
 +
If we try incorrect conversion to <code>Char</code>, we get the following result.
 +
<syntaxhighlight lang="Haskell" class="myDark" >
 +
Prelude> :type (5 + 8) :: Char
 +
 
 +
<interactive>:1:2: error:
 +
    * No instance for (Num Char) arising from a use of `+'
 +
    * In the expression: (5 + 8) :: Char
 +
</syntaxhighlight>
 +
For this particular expression, also the type <code>Double</code> works.
 +
<syntaxhighlight lang="Haskell" class="myDark" >
 +
Prelude> :type (5 + 8) :: Double
 +
(5 + 8) :: Double :: Double
 +
</syntaxhighlight>

Revision as of 12:30, 12 September 2019

Types

  1. Using the GHCi command :info, learn the type of the following functions (and operators): +, sqrt, succ, max
  2. Get the information about the data type of following expressions and evaluate them. it is possible using the command :type. You can switch this option on for all commands by :set +t (removing by :unset +t).
5 + 8 
3 * 5 + 8
2 + 4
sqrt 16 
succ 6
succ 7
pred 9
pred 8
sin (pi / 2)
truncate pi
round 3.5
round 3.4 
floor 3.7 
ceiling 3.3
odd 3
  1. At presentations, we have spoken about some basic types: Int, Double, Bool, Char. For each of previous expressions assign them the most appropriate of these basic data types. You can verify your guess by using ::. For example, for the first expression, lets assume it is Int. We can cast the result to integer and get following result.
Prelude> :type (5 + 8) :: Int
(5 + 8) :: Int :: Int

If we try incorrect conversion to Char, we get the following result.

Prelude> :type (5 + 8) :: Char

<interactive>:1:2: error:
    * No instance for (Num Char) arising from a use of `+'
    * In the expression: (5 + 8) :: Char

For this particular expression, also the type Double works.

Prelude> :type (5 + 8) :: Double
(5 + 8) :: Double :: Double