我想定义似乎需要无限类型的东西.
必需:一个函数"吃"吃掉它除了"3"之外的所有参数,它返回3
eat 3 = 3
eat x = eat
Run Code Online (Sandbox Code Playgroud)
所以基本上像"吃(+)foldl(Just 5)3"这样的任意表达式评估为3.但这里的问题是吃的类型.应该是什么?
我得到的最接近的运行代码是:
newtype Rec = MakeRec (Int -> Rec)
eat :: Int -> Rec
eat x = MakeRec eat
instance Show Rec where
show _ = "EAT"
Run Code Online (Sandbox Code Playgroud)
这适用于"吃6"而不是"吃6 7",如果我把(吃3 = 3)放在它的定义中它就不起作用.
我不确定这在Haskell中是否可行.(用什么论证来表明它是不可能的?)
更新:如下面的解决方案中所述,在编译时需要类型信息,以便编译器可以知道"eat foldl 3 foldl"是否无效.因此,这个问题的确切解决方案是不可能的.
在org-mode中进行html-export时,多个空格被压缩到一个空格.有没有办法更改此默认行为.(我不希望用nbsp替换额外的空格)
我想创建一个名为Linear的Num超类
class Linear a where
add :: a -> a -> a
instance (Num a) => Linear a where
add = (+)
Run Code Online (Sandbox Code Playgroud)
我收到错误:
Illegal instance declaration for `Linear a'
(All instance types must be of the form (T a1 ... an)
where a1 ... an are *distinct type variables*,
and each type variable appears at most once in the instance head.
Use -XFlexibleInstances if you want to disable this.)
In the instance declaration for `Linear a'
Run Code Online (Sandbox Code Playgroud)
根据我的理解,关于这条线的事情instance (Num a) …
假设我们有一个这样的程序:
list = [1..10000000]
main = print $ sum list
Run Code Online (Sandbox Code Playgroud)
我想要编译这样,可执行文件只打印50000005000000,而不需要花费太多时间和精力.
基本上,任何可以确定计算的表达式(也许严格性分析可以在这里帮助)都可以在编译期间预先计算(即我们使用参考透明度来表示在计算值时它并不重要).
简而言之:"必须计算"+参考 - 透明度=可以预先计算
这就像运行程序,直到我们点击依赖于输入的东西(即程序的核心,在所有输入中共同的,将被预先计算)
是否存在当前实现此目的的机制(使用Haskell或任何其他语言)?[请不要指向C++中的模板之类的东西,因为它首先没有引用透明度.]
如果没有,这个问题有多难?[伴随的技术(和理论)问题是什么?]
haskell库中是否有任何函数在O(n)时间内对整数进行排序?[By,O(n)我的意思是比比较排序更快,特定于整数]
基本上我发现下面的代码花了很多时间进行排序(与没有排序的列表相加):
import System.Random
import Control.DeepSeq
import Data.List (sort)
genlist gen = id $!! sort $!! take (2^22) ((randoms gen)::[Int])
main = do
gen <- newStdGen
putStrLn $ show $ sum $ genlist gen
Run Code Online (Sandbox Code Playgroud)
总结一个列表不需要deepseq,但我想要的是,但上面的代码对于我正在寻找的指针来说已经足够了.
时间:6秒(不排序); 约35秒(有排序)
内存:大约80 MB(没有排序); 约310 MB(有排序)
注1:对于我来说,内存对于我来说是一个比时间更大的问题,因为手头的任务我出现了内存错误(内存使用量变为3GB!运行时间为30分钟后)
我假设更快的算法也会提供下注内存打印,因此寻找O(n)时间.
注2:我正在寻找Int64的快速算法,尽管其他特定类型的快速算法也会有所帮助.
使用的解决方案:带有未装箱的向量的IntroSort足以完成我的任务:
import qualified Data.Vector.Unboxed as V
import qualified Data.Vector.Algorithms.Intro as I
sort :: [Int] -> [Int]
sort = V.toList . V.modify I.sort . V.fromList
Run Code Online (Sandbox Code Playgroud) 我有一个"Shape"类,它应该在所有实例上定义"area".area返回"区域b"(数据类型),其中包含一个数字(b属于Num类型类),表示该Shape的区域.
Haskell有问题将b绑定到(x*y),其中x和y的类型为'a',而'a'也是类型类型Num.我该如何解决这个问题?[如果我将(x*y)替换为0,它可以工作,但即使用(0 :: Int)]也不起作用
代码:
data Unit = Unit | Meter | CentiMeter deriving Show
data Area a = Area a Unit deriving Show
class Shape a where
area :: (Num b) => a -> Area b
data Rectangle side = Rectangle side side Unit deriving Show
instance (Num a) => Shape (Rectangle a) where
area (Rectangle x y unit) = Area (x*y) unit
Run Code Online (Sandbox Code Playgroud)
错误:
[1 of 1] Compiling Main ( y.hs, interpreted )
y.hs:11:46:
Could not deduce (a ~ …Run Code Online (Sandbox Code Playgroud)