Применить функцию к каждому элементу списка - это просто:
map _ [] = []
map f (x:xs) = f x : map f xs
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')) |
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 |
{-# LANGUAGE ScopedTypeVariables #-} | |
foo :: forall a. Eq a => [a] -> Bool | |
foo (x:y:_) = x == y | |
foo [_] = foo ([] :: [a]) | |
foo [] = False |
Ответ на вопрос в этом посте.
Для начала слегка модифицируем код, чтоб он компилировался.
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) |
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 |
-- GHC/Base.lhs | |
map _ [] = [] | |
map f (x:xs) = f x : map f xs |