haskellrank – hackerrank haskell
Imperative style (wrong)
Haskell is about declarative programming, not imperative.
|
|
|
|
15
interact
function
Takes a function that takes string and returns a string and applies a side-effect to the output (typically, printing to screen).
|
|
interact :: (String -> String) -> IO ()
dollar operator
|
|
($) :: (a -> b) -> a -> b
We will use this operator to separate interact from its argument.
Declarative style (correct)
|
|
|
|
3
Explanation
|
|
The words function takes a single string and splits it up into tokens (a list of strings).
|
|
words :: String -> [String]
|
|
|
|
Troubleshooting
|
|
/tmp/file_tempfile_4xJeY1_rand-14847_pid-15518.hs:1:1: error:
Parse error: module header, import declaration
or top-level declaration expected.
|
1 | words "foo bar baz"
| ^^^^^^^^^^^^^^^^^^^
|
|
["foo","bar","baz"]
A top-level declaration is something like main =
.
|
|
Array sum
hs | d |
---|---|
words |
read tokens |
tail |
remove the first element |
map read |
convert string elements to numbers |
sum |
take the sum |
show |
convert back to string |
interact |
connect the algorithm to stdin and stdout |
|
|
|
|
31
A very big sum
The type Integer
has arbitrary precision.
It automatically scales when the sum grows.
|
|
data Integer
= integer-gmp-1.0.2.0:GHC.Integer.Type.S# GHC.Prim.Int#
| integer-gmp-1.0.2.0:GHC.Integer.Type.Jp# {-# UNPACK #-}integer-gmp-1.0.2.0:GHC.Integer.Type.BigNat
| integer-gmp-1.0.2.0:GHC.Integer.Type.Jn# {-# UNPACK #-}integer-gmp-1.0.2.0:GHC.Integer.Type.BigNat
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
instance Eq Integer
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
instance Ord Integer
-- Defined in ‘integer-gmp-1.0.2.0:GHC.Integer.Type’
instance Show Integer -- Defined in ‘GHC.Show’
instance Read Integer -- Defined in ‘GHC.Read’
instance Enum Integer -- Defined in ‘GHC.Enum’
instance Num Integer -- Defined in ‘GHC.Num’
instance Real Integer -- Defined in ‘GHC.Real’
instance Integral Integer -- Defined in ‘GHC.Real’
|
|
|
|
5000000015
Grading students
|
|
|
|
2
mod :: Integral a => a -> a -> a
|
|
|
|
75
67
40
33
Collapsed a condition
|
|
unlines :: [String] -> String
|
|
75
67
40
33
Can be written like this
|
|
75
67
40
33
Thanks for reading!
If this article appears incomplete, it may be intentional. Try prompting for a continuation.
If this article appears incomplete, it may be intentional. Try prompting for a continuation.