Scala style val in Haskell

In Scala, I can express a function that evaluates every time I access it:

def function = 1 + 2 + 3

or a val, which evaluated only once

val val1 = 1 + 2 + 3

even if I name it many times.

In Haskell, I can of course define a function (which is evaluated again and again when I call it):

function = 1 + 2 + 3

Can I define a Scala analogue valin Haskell?

UPDATE: the question is not lazy assessment.

UPDATE2:

How many times will the value be evaluated function?

function = 1 + 2 + 3
main = do
        print function
        print function
        print function
+4
source share
3 answers

Haskell . , GHC CAF ( ). , ( ) function = 1 + 2 + 3 function CAF, function .

, , , . ( .)

+19

:

let x = 1 + 2 + 3 in ...

let myFunc () = 1 + 2 + 3 in ...

Haskell , , , , , , ,

Haskell Scala , Scala val x = 1 + 2 + 3 Scala 1 + 2 + 3 . Haskell, , let x = 1 + 2 + 3 1 + 2 + 3 x, , , let .

Haskell , , , , Scala.

+7

EDIT: . . , , ghc -O0 -ddump-simpl main.hs fib Core:

Main.fib :: forall a_agB. GHC.Num.Num a_agB => () -> [a_agB]

O2 optimizations ghc -O2 -ddump-simpl main.hs

Main.$wfib :: forall a_agG. GHC.Num.Num a_agG => [a_agG]

Fibonacci ( ())

Main.fib =
  \ (@ a_agG) (w_stM :: GHC.Num.Num a_agG) (w1_stN :: ()) ->
    case w1_stN of _ { () -> Main.$wfib @ a_agG w_stM }

, Main.fib memoized, Main.$wfib .


:

, ,

val = 1+2+3

, . , ,

val () = 1+2+3

, () val, . , val , , . , :

fib = 0 : 1 : zipWith (+) fib (tail fib)

fib !! 100000, 100 000 . fib , , . ,

fib () = let x = 0 : 1 : zipWith (+) x (tail x) in x

fib () , , .

Edit: as Philippe JF said in the comments, the contents of the let statement could be stripped by an unfriendly compiler, resulting in unwanted sharing

+2
source

All Articles