Haskell. Strict application $!

I run the following code:

(take 10) $! [1,2..]

What is it? I thought ghc would give in, because I say "rate [1,2 ..] power." But I got the result "[1,2,3,4,5,6,7,8,9,10]".

+3
source share
3 answers

So, you expect the list to be fully appreciated. ($!) is implemented in terms seq, and seq"only" evaluates the head of the normal form in accordance with the documents. This will make a difference if the value is undefined:

Prelude> take 0 undefined
[]
Prelude> take 0 $! undefined
*** Exception: Prelude.undefined

A function is strictly by argument if

f undefined = undefined

This does not mean that the argument is fully appreciated with impatience. What you want is something like DeepSeq .

GHCi, version 6.10.1: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer ... linking ... done.
Loading package base ... linking ... done.
[1 of 1] Compiling DeepSeq          ( deepSeq.lhs, interpreted )
Ok, modules loaded: DeepSeq.
*DeepSeq> take 1 $!! [1,2,undefined]
*** Exception: Prelude.undefined
*DeepSeq> 

$!! DeepSeq .

+12

, [1,2..] . [1,2..] (1:_), , , , [1,2,3,4,5,6,7,8,9,10].

, 1; GHCi?

+4

Did you enter something wrong? It works for me with or without parentheses under GHCi 6.8.2 ...

GHCi, version 6.8.2: http://www.haskell.org/ghc/  :? for help
($Loading package base ... linking ... done.
Prelude> take 10 $! [1..]
[1,2,3,4,5,6,7,8,9,10]
Prelude> (take 10) $! [1..]
[1,2,3,4,5,6,7,8,9,10]
Prelude> (take 10) $! [1,2..]
[1,2,3,4,5,6,7,8,9,10]
+2
source

Source: https://habr.com/ru/post/1720350/


All Articles