Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Haskell有更好的方法吗?_Haskell_Integer Arithmetic - Fatal编程技术网

在Haskell有更好的方法吗?

在Haskell有更好的方法吗?,haskell,integer-arithmetic,Haskell,Integer Arithmetic,我写了以下内容来帮助孙子们完成家庭教育工作,并通过学习如何编程来保持头脑工作(我认为haskell听起来很棒) main::IO() main=do putStrLn“请输入股息:” inputx它将受益于一个关键原则:尽可能将纯代码与IO分离。这将允许您的程序扩展并保持mainbreif。在大型main中使用大量let不是一种非常实用的方法,而且随着代码的增长,这种方法往往会变得更加混乱 使用类型签名和本质上是fmap read getLine的readLn有助于减少一些积垢。(如果您不熟悉f

我写了以下内容来帮助孙子们完成家庭教育工作,并通过学习如何编程来保持头脑工作(我认为haskell听起来很棒)

main::IO()
main=do
putStrLn“请输入股息:”

inputx它将受益于一个关键原则:尽可能将纯代码与IO分离。这将允许您的程序扩展并保持
main
breif。在大型
main
中使用大量
let
不是一种非常实用的方法,而且随着代码的增长,这种方法往往会变得更加混乱

使用类型签名和本质上是fmap read getLine的
readLn
有助于减少一些积垢。(如果您不熟悉
fmap
,请访问问题。
fmap
确实是一个非常灵活的工具。)

拼图的最后一块是输出。同样,我更喜欢在IO外部生成该文件,然后我可以稍后在其上打印每一行。我更愿意采用记录类型,但我允许字符串列表作为输入,因为我假设我已经显示了所有字符串

explain :: [String] -> [String]
explain [x,y,q,r,yq,yq_r] = 
  [ concat ["Result: ", x, " / ", y, " =  ", q, " remainder ", r]
  , concat ["Proof: (", y, " x ", q, ") + ", r, " = ", yq, " + ", r, " = ", yq_r]
  , "Is this what you had? "]
现在我们可以将
main
编写为

main = do (x,y) <- getInts
          let ns = map show ( sums (x,y) )
              es = explain ns
          mapM_ putStrLn es

您可能会注意到,我在证明中添加了一个
+r
,使
=
始终表示
=
,这是正确的数学用法,mirror的Haskell表示=

我想没关系,你可以缩短一些零件(例如,merge
read
getLine
-使用和
div
/
mod
使用-但我认为这样一个简单的程序很好样式主要是一个首选项,但我会做以下事情:
input>getLine
;顺序let语句不需要在每行上都使用let。)(即将第一行之后的所有let替换为3个空格),而不是按顺序使用
putStrLn
,我将编写
putStrLn$“第1行”+“第2行”+“第3行”
(每个字符串可以在自己的行上-只要以下行缩进,haskell就知道同一语句中它的部分)@user2407038您的
putStrLn
将错过一些换行;),因为您没有验证输入(以查看它是否真的可以解析为字符串)无论如何,您最好直接使用readLn而不是getLine。您可能会得到更全面的回复,这是一个专门用于代码审查的网站。谢谢@WillNess,您的编辑总是很好,总是受欢迎的。谢谢,Andrew,我不再问了。:)
sums :: (Int, Int) -> [Int]
sums (x,y) = [x, y, q, r, y * q, y * q + r] where
            q = x `div` y
            r = x `mod` y
explain :: [String] -> [String]
explain [x,y,q,r,yq,yq_r] = 
  [ concat ["Result: ", x, " / ", y, " =  ", q, " remainder ", r]
  , concat ["Proof: (", y, " x ", q, ") + ", r, " = ", yq, " + ", r, " = ", yq_r]
  , "Is this what you had? "]
main = do (x,y) <- getInts
          let ns = map show ( sums (x,y) )
              es = explain ns
          mapM_ putStrLn es
main :: IO ()
main = fmap (explain . map show . sums) getInts
       >>= mapM_ putStrLn