【问题标题】:Function that returns a list of words of length n返回长度为 n 的单词列表的函数
【发布时间】:2018-06-02 13:29:40
【问题描述】:

嘿,我是 Haskell 的新手,想弄清楚如何返回一个长度为 n 的单词的列表

getWords :: Int -> [Word] -> [Word]
getWords n w = filter (\x -> length x == n) w

我发现我可以在 Prelude 中使用它 过滤器 (\x -> 长度 x == 5) ["Hello", "23"]

它会返回 ["Hello"],但是当我尝试在函数 getWords 中执行此操作时,它会给我一个错误

* Couldn't match type `t0 a0' with `Word'
      Expected type: [Word]
        Actual type: [t0 a0]
    * In the expression: filter (\ x -> length x == n) w
      In an equation for `getWords':
          getWords n w = filter (\ x -> length x == n) w
    |
163 | getWords n w = filter (\x -> length x == n) w
    |                ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Date.hs:163:45: error:
    * Couldn't match type `Word' with `t0 a0'
      Expected type: [t0 a0]
        Actual type: [Word]
    * In the second argument of `filter', namely `w'
      In the expression: filter (\ x -> length x == n) w
      In an equation for `getWords':
          getWords n w = filter (\ x -> length x == n) w
    |
163 | getWords n w = filter (\x -> length x == n) w

我在这里做错了什么?

【问题讨论】:

  • 您希望"Hello" 具有什么类型?根据 Haskell 文档,Word 是哪种数据类型?
  • 在这种情况下是Word 只是String 还是[Char]
  • Word 是数字类型,除非您以某种方式重新定义了它。你想要一个字符串列表,即getWords :: Int -> [String] -> [String]
  • @RoadRunner 没关系; type String = [Char].

标签: list haskell


【解决方案1】:

你做错了什么是使用Word 大概来自Data.Word。这是一个机器字,如无符号整数值。它不是一个人类单词,就像字符串中的字母一样。正如@chi 在 cmets 中所述,您应该使用[String]

getWords :: Int -> [String] -> [String]
getWords n w = filter (\x -> length x == n) w

【讨论】:

  • 我是从books.google.com.au/…这本书里得到的
  • 据我所知,这本书甚至没有定义Word,所以我不确定作者想要在那里。
  • 啊,错误表明提问者没有使用该类型别名。如果他们包含该别名并使用现代 GHC,那么我们会看到 Ambiguous occurrence ‘Word’
猜你喜欢
  • 2017-06-23
  • 2014-04-13
  • 1970-01-01
  • 2020-07-12
  • 2021-05-19
  • 2013-01-16
  • 2018-01-20
  • 2021-03-13
  • 2016-03-14
相关资源
最近更新 更多