我想从懒惰列表中获取n个最大的元素.
我听说在Data.List.sort中实现的mergesort是惰性的,它不会产生超过必要的元素.这在比较方面可能是正确的,但在内存使用方面肯定不是这样.以下程序说明了该问题:
{-# LANGUAGE ScopedTypeVariables #-}
module Main where
import qualified Data.Heap as Heap
import qualified Data.List as List
import System.Random.MWC
import qualified Data.Vector.Unboxed as Vec
import System.Environment
limitSortL n xs = take n (List.sort xs)
limitSortH n xs = List.unfoldr Heap.uncons (List.foldl' (\ acc x -> Heap.take n (Heap.insert x acc) ) Heap.empty xs)
main = do
st <- create
rxs :: [Int] <- Vec.toList `fmap` uniformVector st (10^7)
args <- getArgs
case args of
["LIST"] -> print (limitSortL …
Run Code Online (Sandbox Code Playgroud) Gtk2hs具有各种实现Widget类的小部件数据类型.是否可以编写自定义数据类型?
假设我想拥有用于显示和运行Lua代码的小部件.
data LuaWidget = LuaWidget { text :: TextView, package :: HBox } deriving Eq
instance Widget LuaWidget where
....
Run Code Online (Sandbox Code Playgroud)
是否可以在Haskell级别上?
我已经定义了以下模块来帮助我进行FFI功能导出:
{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances #-}
module ExportFFI where
import Foreign
import Foreign.C
class FFI basic ffitype | basic -> ffitype where
toFFI :: basic -> IO ffitype
fromFFI :: ffitype -> IO basic
freeFFI :: ffitype -> IO ()
instance FFI String CString where
toFFI = newCString
fromFFI = peekCString
freeFFI = free
Run Code Online (Sandbox Code Playgroud)
我正在努力实现函数的实例.有人能帮我吗?
我想用System.Random.MWC.Monad中的 Rand monad生成无限的数字流.如果只有这个monad的MonadFix实例,或者像这样的实例:
instance (PrimMonad m) => MonadFix m where
...
Run Code Online (Sandbox Code Playgroud)
然后人们可以写:
runWithSystemRandom (mfix (\ xs -> uniform >>= \x -> return (x:xs)))
Run Code Online (Sandbox Code Playgroud)
虽然没有一个.
我正在浏览MonadFix文档,但我没有看到实现此实例的明显方法.
我希望有一个类型类型,可能在可能的情况下转换为其他类型.
class Castable a b where
cast :: a -> Maybe b
cast _ = Nothing -- default implementation
Run Code Online (Sandbox Code Playgroud)
现在,该类将针对某些类型实现,对于所有其他类型,我希望具有默认实现.
怎么能这样做?