我正在用JavaScript编写一个程序来计算6位数的数字,其前3位数的总和等于最后3位数的总和.所以我为问题写了两个不同的解决方案,尽管只有一个会返回正确答案.
我还编写了一个函数sumOfDigits(),它只是计算传递给它的数字的总和.此功能不在这里写,但它的工作正确.
function count1() {
total=0;
for (i = 100000; i <= 999999; i+=1) {
part = i % 1000;
if ((sumOfDigits(i-part)) == ((sumOfDigits(part)))) {
total+=1;
}
} return total;
}
Run Code Online (Sandbox Code Playgroud)
function count2() {
array = [];
for (i = 100000; i <= 999999; i+=1) {
part = i % 1000;
if ((sumOfDigits(i-part)) == ((sumOfDigits(part)))) {
array.push(i);
}
} return array;
}
Run Code Online (Sandbox Code Playgroud)
该count1()函数无法正常工作并返回28作为答案,而count2()返回数组的函数返回长度为50412的数组,这是正确的答案.有人可以告诉我为什么第一个功能无法正常工作.
正在count1运行的功能的屏幕截图.

这个内存泄漏是由fopen()引起的吗?我使用 fclose() 关闭 FILE* 指针,但这个问题仍然存在。
==32379== Memcheck, a memory error detector
==32379== Copyright (C) 2002-2012, and GNU GPL'd, by Julian Seward et al.
==32379== Using Valgrind-3.8.1 and LibVEX; rerun with -h for copyright info
==32379== Command: ./speller /home/cs50/pset6/texts/austinpowers.txt
==32379==
==32379==
==32379== HEAP SUMMARY:
==32379== in use at exit: 352 bytes in 1 blocks
==32379== total heap usage: 510,177 allocs, 510,176 frees, 57,140,478 bytes allocated
==32379==
==32379== 352 bytes in 1 blocks are still reachable in loss record 1 of 1 …Run Code Online (Sandbox Code Playgroud) 我很难理解liftM2haskell的工作原理。我编写了以下代码,但未输出任何内容。
import Control.Monad
main = liftM2 (\a b -> putStrLn$show$(+) a b) readLn readLn
Run Code Online (Sandbox Code Playgroud) 我似乎无法理解如何id将其用作某些高阶函数的参数.我曾经在某个地方读到它曾经"习惯于"留下一些东西",但似乎无法理解它.
例如,为什么是这种类型的liftA2 id f (b -> c) -> f b -> f c?
另外,为什么我不能传递id到g了
g :: (Int -> Int -> Int) -> Int -> Int -> Int
Run Code Online (Sandbox Code Playgroud)
?

为什么这发生在我身上?我在python和chrome的JS控制台中乘以相同的数字但似乎JS忘记了如何计算.
function arrayToList(array){
LIST = {};
function add(list, index){
if(index < array.length){
list = {value:array[index], rest : null};
add(list.rest, index+1);
}
}
add(LIST,0);
return LIST;
}
Run Code Online (Sandbox Code Playgroud) 为什么用这种方式使用foldr编写地图
map' :: (a -> b) -> [a] -> [b]
map' f xs = foldr (\x acc -> f x : acc) []
Run Code Online (Sandbox Code Playgroud)
给出以下错误?
test.hs:2:13: error:
• Couldn't match expected type ‘[b]’ with actual type ‘t0 a -> [b]’
• Probable cause: ‘foldr’ is applied to too few arguments
In the expression: foldr (\ x acc -> f x : acc) []
In an equation for ‘map'’:
map' f xs = foldr (\ x acc -> f x : acc) …Run Code Online (Sandbox Code Playgroud)