Scott Wlaschin ThinkOfNumber示例

时间:2018-11-19 09:17:01

标签: haskell

我正在尝试使用haskell进行函数式编程。 我看过Scott Wlaschin的这段精彩视频https://www.youtube.com/watch?v=vDe-4o8Uwl8。 我正在尝试使用haskell实现他的ThinkOfNumber示例。

Think of a number, F#

我找到的唯一解决方案是这个:

thinkOfANumber  numberYouThoughtOf =  (\x -> x - numberYouThoughtOf) 
                                      . (\x -> x / numberYouThoughtOf) 
                                      . (\x -> x - 1) 
                                      . (\x -> x * x) 
                                      . (\x -> x + 1)

所以我必须使用2个参数以这种方式调用函数

thinkOfANumber 13 13

为了记住呼叫链中的号码YouThoughtOf。

我有一种简化代码的方法,可以在F#中使用类似管道的运算符,例如“ |>”运算符?

也许我肯定错过了一些东西:) 问候。 伊万

在Fyodor Soikin的良好回应后进行编辑:

如果有人对Scott Wlaschin演示文稿感兴趣,这是toRomanNumerals示例的一种haskell解决方案:

import Data.List.Utils

  infixl 5 |>
  x |> f = f x

  toRomanNumerals number = 
      let replicate_I     = ['I' | _ <- [1 .. number]]
          replace_IIIII_V = replace "IIIII" "V"
          replace_VV_X    = replace "VV" "X"
          replace_XXXXX_L = replace "XXXXX" "L"
          replace_LL_C    = replace "LL" "C"
          replace_CCCCC_D = replace "CCCCC" "D"
          replace_DD_M    = replace "DD" "M"
      in replicate_I
         |> replace_IIIII_V
         |> replace_VV_X
         |> replace_XXXXX_L
         |> replace_LL_C
         |> replace_CCCCC_D 
         |> replace_DD_M

再次感谢fyodor soikin!

2 个答案:

答案 0 :(得分:2)

Data.Function中的

Operator &是F#管道的确切模拟物:

thinkOfANumber numberYonThoughOf = 
    let addOne x = x + 1
        squareIt x = x * x
        subtractOne x = x - 1
        divideByTheNumberYouThoughtOf x = x / numberYonThoughOf
    in  numberYonThoughOf 
        & addOne
        & squareIt
        & subtractOne
        & divideByTheNumberYouThoughtOf

当然,如果您喜欢管道(我个人喜欢),则始终可以在Haskell中对其进行定义:

infixl 5 |>
x |> f = f x

thinkOfANumber numberYonThoughOf = 
    let addOne x = x + 1
        squareIt x = x * x
        subtractOne x = x - 1
        divideByTheNumberYouThoughtOf x = x / numberYonThoughOf
    in  numberYonThoughOf 
        |> addOne
        |> squareIt
        |> subtractOne
        |> divideByTheNumberYouThoughtOf

答案 1 :(得分:1)

Fyodor Soikin是正确的,&对应于F#的|>,但是我从阅读Haskell代码中得到的印象是,使用$运算符并从右向左组合更习惯,就像在数学中一样:

thinkOfANumber numberYouThoughOf = 
  let addOne x = x + 1
      squareIt x = x * x
      subtractOne x = x - 1
      divideByTheNumberYouThoughtOf x = x / numberYouThoughOf
  in divideByTheNumberYouThoughtOf $ subtractOne $ squareIt $ addOne numberYouThoughOf