我正在学习Ruby,并考虑制作二进制 - >十进制转换器.它获取二进制字符串并转换为十进制等效值.有没有办法跟踪ruby中的当前迭代步骤,以便可以删除变量'x'?
def convert(binary_string)
decimal_equivalent = 0
x=0
binary_string.reverse.each_char do |binary|
decimal_equivalent += binary.to_i * (2 ** x)
x+=1
end
return decimal_equivalent
end
Run Code Online (Sandbox Code Playgroud) 现在我有
return 'Heads' if Math.random() < 0.5
Run Code Online (Sandbox Code Playgroud)
有一个更好的方法吗?
谢谢
编辑:请忽略返回值,"更好"意味着准确的50-50概率.
我正在从网上检索HTML.我得到"java.lang.OutOfMemoryError: Java heap space (repl-1:3)"
;; fetch: URL -> String
;; fetch returns the string of the HTML url
(defn fetch [url]
(with-open [stream (. url openStream)]
(let [buffer (BufferedReader. (InputStreamReader. stream))]
(apply str (line-seq buffer)))))
Run Code Online (Sandbox Code Playgroud)
我认为问题是"应用str".有没有更简单的方法
编辑:我需要检索
现在我有
;; buffer->string: BufferedReader -> String
(defn buffer->string [buffer]
(loop [line (.readLine buffer) sb (StringBuilder.)]
(if(nil? line)
(.toString sb)
(recur (.readLine buffer) (.append sb line)))))
Run Code Online (Sandbox Code Playgroud)
这太慢了.
编辑:
我有一个BufferedReader
当我尝试做(str BufferedReader)它给了我"java.io.BufferedReader@1ce784b"
上面的循环太慢了,我的内存空间不足.
在维基百科中的内联函数问题:http: //en.wikipedia.org/wiki/Inline_expansion#Problems
它说:"#语言规范可能允许程序对程序的参数做出额外的假设,这些程序在内联程序后就无法再进行."
有人可以详细阐述这一点吗?
你如何阻止GCC内联C++函数?
我有一个具有此功能的Abstract Iterator类
void iterate(){
while(this.hasnext()){
..this.next()..
}
}
Run Code Online (Sandbox Code Playgroud)
如何传入将应用于下一个元素的任意函数.例如,有办法iterate(print)
吗?
你们能想到全功能的最短和最惯用的解决方案吗?
;; all-but-one
;; checks if all but one element in a list holds a certain property
;; (all-but-one even? (list 1 2 4)) -> true
;; (all-but-one even? '(1)) -> true
;; (all-but-one even? '(2 4)) -> false
Run Code Online (Sandbox Code Playgroud)
编辑:完全是一个.
我有这个,但我收到一个错误:
-- test if a list contains exactly three characters
test :: [Char] -> Bool
test xs | [_ , _ , _] = True
| otherwise = False
Run Code Online (Sandbox Code Playgroud) -- eg. myzip [’a’, ’b’, ’c’] [1, 2, 3, 4] -> [(’a’, 1), (’b’, 2), (’c’, 3)]
myzip :: Ord a => [a] -> [a] -> [(a,a)]
myzip list1 list2 = [(x,y) | [x, _] <-list1, [y,_] <-list2 ]
Run Code Online (Sandbox Code Playgroud)
我收到此错误消息:
Occurs check: cannot construct the infinite type: a = [a]
When generalising the type(s) for `myzip'
Failed, modules loaded: none.
Run Code Online (Sandbox Code Playgroud) 我想要一个静态内部类,即使是外部类也无法实例化.现在我只有一个文档说"请不要实例化这个对象".我可以给出更好的信号吗?