Skip to content

Instantly share code, notes, and snippets.

module Main(main) where
foo :: [()] -> ()
foo x = bar x where
bar x = {-# SCC "my" #-} head x
main = print $ foo []
{-
*** Exception (reporting due to +RTS -xc): (THUNK_2_0), stack trace:
> List.map ((+)1) [1..10000000];;
Real: 00:00:06.655, CPU: 00:00:07.328, GC gen0: 83, gen1: 64, gen2: 3
val it : int list =
[2; 3; 4; 5; 6; 7; 8; ...]
> let map_cps f l' =
- let rec go l c =
- match l with
- | [] -> c []
- | (x::xs) -> go xs (fun xs' -> c (f x :: xs'))
@klapaucius
klapaucius / _post.md
Last active November 7, 2021 22:36
spine-strict_lists

Строгость и нищета списков.

Map и структурная рекурсия.

Применить функцию к каждому элементу списка - это просто:

GHC/Base.lhs

map _ []     = []
map f (x:xs) = f x : map f xs
foo :: Eq a => [a] -> Bool
foo (x:y:_) = x == y
foo [_] = foo ([] :: [a])
foo [] = False
class Functor f where
type C f a :: Constraint
type C f a = ()
fmap :: (C f a, C f b) => (a -> b) -> f a -> f b
-- Инстансы для "неограниченных" функторов остались без изменений:
instance Functor [] where
fmap = map
instance Functor Set where
@klapaucius
klapaucius / gist:1393019
Created November 25, 2011 07:56
true-signature
{-# LANGUAGE ScopedTypeVariables #-}
foo :: forall a. Eq a => [a] -> Bool
foo (x:y:_) = x == y
foo [_] = foo ([] :: [a])
foo [] = False
@klapaucius
klapaucius / post.md
Created November 17, 2011 18:43
! vs unsafeIndex

Ответ на вопрос в этом посте.

Для начала слегка модифицируем код, чтоб он компилировался.

import qualified Data.List.Stream as S
import qualified Data.Vector.Unboxed as U

f n = let arr = U.enumFromTo 1 n 
      in S.sum $ S.map (\i -> arr U.! (i `rem` n)) $ S.unfoldr (\i -> if i < n then Just (i, i+1) else Nothing) 0
$s$wfoldlM'_loop_s1qP =
\ (sc_s1qv :: GHC.Prim.Int#)
(sc1_s1qw :: GHC.Prim.Int#)
(sc2_s1qx :: GHC.Prim.Double#) ->
case GHC.Prim.>=# sc1_s1qw ipv1_s1a1 of _ {
GHC.Bool.False ->
case GHC.Prim.>=# sc_s1qv ipv4_s1fy of _ {
GHC.Bool.False ->
$s$wfoldlM'_loop_s1qP
(GHC.Prim.+# sc_s1qv 1)
@klapaucius
klapaucius / gist:1319163
Created October 27, 2011 09:31
in-place quick sort
import Data.Vector.Generic
import qualified Data.Vector.Generic.Mutable as M
iqsort :: (Vector v a, Ord a) => v a -> v a
iqsort = modify go where
go xs | len < 2 = return ()
| otherwise = do
p <- xs `M.read` (len `div` 2)
m <- M.unstablePartition (< p) xs
go $ M.slice 0 m xs
@klapaucius
klapaucius / gist:1319154
Created October 27, 2011 09:27
map in haskell
-- GHC/Base.lhs
map _ [] = []
map f (x:xs) = f x : map f xs