Haskell简化技术和单子 [英] Haskell simplification technique and monads

查看:57
本文介绍了Haskell简化技术和单子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何减少/简化此代码(或者通常是具有多个输入的代码)?

How can this code (or in general, code with multiple inputs) can be reduced/simplified?

do
  sex    <- askSex
  name   <- askName
  sayHello sex name

在这种情况下已经很短了,但是当它到达多个输入时,看起来很乱.有没有办法做类似的事情:

In this case is very short already, but when it gets to multiple inputs, it looks messy. Is there any way to do something like:

sayHello askSex askName

?

推荐答案

这是应用函子的美好时光:

This is a lovely time for Applicative Functors:

import Control.Applicative -- at the top of your module before any functions

hello "Male" name = "Hi, " ++ name ++ ", that's a cool name."
hello "Female" name = "Hello, " ++ name ++ ", that's a pretty name."

greet = hello <$> askSex <*> askName >>= putStrLn

它的工作方式有点像我今天给您的先前答案中的fmap,但是对于更多的参数,就像您在这里一样.

It works a bit like fmap in the previous answers I gave you today, but for larger numbers of arguments, like you have here.

将类似我的hello的函数与应用函子结合使用,可以帮助您将IO代码与其余代码分开,这是一种很好的做法.尝试每次写hello而不是sayHello.

Using functions like my hello with applicative functors helps you separate your IO code from the rest of the code, which is very good practice. Try to write hello instead of sayHello every time.

这篇关于Haskell简化技术和单子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆